Definition
Defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary indenpendently from clients that use it.
Components
- Client: this class uses interchangeable algorithms. It maintains a reference to StrategyBase object.
- StrategyBase: declares an interface common to all supported algorithms.
- ConcreteStrategy:inherited from the StrategyBase Class, provides a different algorithm.
Sample code
public interface Istrategy {
public void operate();
}
public class Strategy1 implements Istrategy{
public void operate(){
System.out.println("operate 1");
}
}
public class Strategy2 implements Istrategy {
public void operate(){
System.out.println("operate 2");
}
}
public class Context {
private Istrategy strategy;
public Context(Istrategy strategy) {
this.strategy = strategy;
}
public void operate() {
this.strategy.operate();
}
}
public class Client {
public static void main(string args[]) {
Context context;
context = new Context (new Strategy1());
context.operate();
context = new Context (new Strategy2());
context.operate();
}
}
Advantages
- Provides design where client and strategies are loosely coupled.
- Easy to add or replace or reuse clients or strategies.
Reference
Design Patterns 1 of 3 - Creational Design Patterns - CodeProject
Head First Design Patterns - O'Reilly Media