strategy pattern


There are common situations when classes differ only in their behavior. For this cases is a good idea to isolate the algorithms in separate classes in order to have the ability to select different algorithms at runtime.

Intent

  • Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.
  • Capture the abstraction in an interface, bury implementation details in derived classes.

Implementation

We are going to create a Strategy interface defining an action and concrete strategy classes implementing the Strategy interface. Context is a class which uses a Strategy.

1
2
3
4
public interface {
public int doOperation(int num1, int num2);
}

1
2
3
4
5
6
7
// OperationAdd.java
public class OperationAdd implements {
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
1
2
3
4
5
6
7
// OperationSubstract.java
public class OperationSubstract implements {
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
// Context.java
public class Context {
private Strategy strategy;
public Context(Strategy strategy){
this.strategy = strategy;
}
public int executeStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
1
2
3
4
5
6
7
8
9
10
// StrategyPatternDemo.java
public class StrategyPatternDemo {
public static void main(String[] args) {
Context context = new Context(new OperationAdd());
System.out.println("10 + 5 = " + context.executeStrategy(10, 5));
context = new Context(new OperationSubstract());
System.out.println("10 - 5 = " + context.executeStrategy(10, 5));
}
}

Reference

TutorialsPoint