Intent
Define a family of algorithms(algo1, algo2, ...);
Encapsulate each one, and make them interchangeable.
Strategy lets algorithms vary independently from clients that use it.
Steps
First, you need to define an interface of IStrategy;
Secondly, you need to create a concrete ClientContext Class to execute the operations in the IStrategy.
Thirdly, concrete implementations class about IStrategy.
// 1. IStrategy interface
public interface IStrategy {
public void operate();
}
//2. ClientContext to execute strategy.
public class ClientContext {
private IStrategy strategy;
public ClientContext(IStrategy strategy){
this.strategy = strategy;
}
public void doOperation(){
this.strategy.operate(); // execute IStrategy method.
}
}
//3. Concrete strategy class.
public class Strategy1 implements IStrategy{
public void operate(){
System.out.println("Strategy 1 is executed.");
}
}
//4. Concrete strategy class. Of course, you can have many strategy classes.
public class Strategy2 implements IStrategy {
public void operate(){
System.out.println("Strategy 2 is executed.");
}
}
// main
public class Test {
public static void main(String[] args){
ClientContext context;
context = new ClientContext(new Strategy1()); // execute strategy1
context.doOperation(); // output: Strategy 1 is executed.
context = new ClientContext(new Strategy2()); // execute strategy2.
context.doOperation(); // output: Strategy 2 is executed.
}
}