Strategy pattern using Enums. Need a simple example in Java -
this question has reply here:
where benefit in using strategy pattern? 8 answersi'm trying understand strategy pattern , enums in java. i've googled , have found few articles on subject, of them seemed complex understanding. provide simple illustration or link demonstrates strategy pattern using enums in laymen terms using java?
thanks in advance.
this should do:
interface strategy { int execute(int a, int b); } enum math implements strategy { add together { @override public int execute(int a, int b) { homecoming + b; } }, subtract { @override public int execute(int a, int b) { homecoming - b; } }, multiply { @override public int execute(int a, int b) { homecoming * b; } }; } it re-implementation of wikipedia article using enum strategies.
or little longer more strategy pattern:
public interface failurestrategy { void fail (string message); } enum failure implements failurestrategy { ignore { @override public void fail(string message) { // nil on success. } }, logtoconsole { @override public void fail(string message) { system.out.println(message); } }, errtoconsole { @override public void fail(string message) { system.err.println(message); } }, ringalarmbells { @override public void fail(string message) { // left student. } }, soundtheklaxon { @override public void fail(string message) { // left student. } }, endtheworld { @override public void fail(string message) { // left student. } }; } public class somethinglethal { public failurestrategy onfail = failure.endtheworld; } public class somethingdangerous { public failurestrategy onfail = failure.ringalarmbells; } public class somethingbenign { public failurestrategy onfail = failure.ignore; } java java-ee design-patterns enums strategy-pattern
No comments:
Post a Comment