I am learning the Strategy pattern but hate the idea of passing a new object to the Context each time I need to change the desired algorithm. Instead I think it would be best to create an enum that holds all of the Concrete Strategy objects, and simply update them with a setter on the context. Below is my implementation. Please let me know if this is a good approach for Strategy?
Client
public class Client {
public static void main(String args[]){
IntroductionContext introductionContext = new IntroductionContext();
introductionContext.setStrategy(ConcreteStrategies.HELLO);
introductionContext.executeStrategy();
introductionContext.setStrategy(ConcreteStrategies.GOODBYE);
introductionContext.executeStrategy();
}
}
Context
public class IntroductionContext {
private IInteractionStrategy iInteractionStrategy;
public void executeStrategy() {
if(iInteractionStrategy == null){
throw new RuntimeException("Context must set its strategy before invoking executeStrategy()");
}
this.iInteractionStrategy.interact();
}
public void setStrategy(ConcreteStrategies concreteStrategy){
this.iInteractionStrategy = (IInteractionStrategy) concreteStrategy.getConcreteStrategy();
}
}
Enum to hold all strategy objects
public enum ConcreteStrategies {
HELLO(new HelloStrategy()), GOODBYE(new GoodByeStrategy());
private Object concreteStrategy;
private ConcreteStrategies(Object concreteStrategy){
this.concreteStrategy = concreteStrategy;
}
public Object getConcreteStrategy(){
return this.concreteStrategy;
}
}
Strategy (Interface)
public interface IInteractionStrategy {
public void interact();
}
Concrete Strategy
public class HelloStrategy implements IInteractionStrategy {
@Override
public void interact() {
System.out.println("Hello!");
}
}
Concrete Strategy
public class GoodByeStrategy implements IInteractionStrategy {
@Override
public void interact() {
System.out.println("Goodbye!");
}
}