Design Pattern 简明教程
Design Patterns - Strategy Pattern
在策略模式中,一个类的行为或其算法可以在运行时更改。这种设计模式属于行为模式。
In Strategy pattern, a class behavior or its algorithm can be changed at run time. This type of design pattern comes under behavior pattern.
在策略模式中,我们创建代表各种策略的对象,以及随其策略对象而行为不同的上下文对象。策略对象更改上下文对象的可执行算法。
In Strategy pattern, we create objects which represent various strategies and a context object whose behavior varies as per its strategy object. The strategy object changes the executing algorithm of the context object.
Implementation
我们将创建定义动作的策略接口和实现该策略接口的具体策略类。Context 是使用策略的类。
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.
策略模式演示,我们的演示类将使用上下文和策略对象根据其部署或使用的策略展示策略变化。
StrategyPatternDemo, our demo class, will use Context and strategy objects to demonstrate change in Context behaviour based on strategy it deploys or uses.
Step 1
创建一个接口。
Create an interface.
Strategy.java
public interface Strategy {
public int doOperation(int num1, int num2);
}
Step 2
创建实现相同接口的具体类。
Create concrete classes implementing the same interface.
OperationAdd.java
public class OperationAdd implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 + num2;
}
}
OperationSubstract.java
public class OperationSubstract implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 - num2;
}
}
OperationMultiply.java
public class OperationMultiply implements Strategy{
@Override
public int doOperation(int num1, int num2) {
return num1 * num2;
}
}
Step 3
创建 Context 类。
Create Context Class.
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);
}
}
Step 4
使用 Context 查看当其更改其 Strategy 时,行为中的变更。
Use the Context to see change in behaviour when it changes its Strategy.
策略模式演示.java
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));
context = new Context(new OperationMultiply());
System.out.println("10 * 5 = " + context.executeStrategy(10, 5));
}
}