I'm trying to understand the strategy pattern and enums in java. I've googled this and have found a few articles on the subject, but most of them seemed too complex for my understanding. Could anyone provide a simple example or another link that demonstrates strategy pattern using enums in laymen terms using java?
Thanks you in advance.
This should do:
interface Strategy {
int execute(int a, int b);
}
enum Math implements Strategy {
Add {
@Override
public int execute(int a, int b) {
return a + b;
}
},
Subtract {
@Override
public int execute(int a, int b) {
return a - b;
}
},
Multiply {
@Override
public int execute(int a, int b) {
return a * b;
}
};
}
It is a re-implementation of the Wikipedia article using enum
for the strategies.
Or a little longer but more clearly a strategy pattern:
public interface FailureStrategy {
void fail (String message);
}
enum Failure implements FailureStrategy {
Ignore {
@Override
public void fail(String message) {
// Do nothing 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 to the student.
}
},
SoundTheKlaxon {
@Override
public void fail(String message) {
// Left to the student.
}
},
EndTheWorld {
@Override
public void fail(String message) {
// Left to the 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;
}