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
publicinterface{
publicintdoOperation(int num1, int num2);
}
1
2
3
4
5
6
7
// OperationAdd.java
publicclassOperationAddimplements{
publicintdoOperation(int num1, int num2){
return num1 + num2;
}
}
1
2
3
4
5
6
7
// OperationSubstract.java
publicclassOperationSubstractimplements{
publicintdoOperation(int num1, int num2){
return num1 - num2;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
// Context.java
publicclassContext{
private Strategy strategy;
publicContext(Strategy strategy){
this.strategy = strategy;
}
publicintexecuteStrategy(int num1, int num2){
return strategy.doOperation(num1, num2);
}
}
1
2
3
4
5
6
7
8
9
10
// StrategyPatternDemo.java
publicclassStrategyPatternDemo{
publicstaticvoidmain(String[] args){
Context context = new Context(new OperationAdd());
近期评论