java 策略模式
//调用者
public class StrategyDemo {
public static void main(String[] args) {
//动态的选择某一种算法策略
Context context1 = new Context(new OperationStrategy1());
context1.executeStrategy();
Context context2 = new Context(new OperationStrategy2());
context2.executeStrategy();
}
}
//策略接口
interface Strategy {
void operate();
}
//策略具体算法实现
class OperationStrategy1 implements Strategy {
@Override
public void operate() {
System.out.println("operation1");
}
}
class OperationStrategy2 implements Strategy {
@Override
public void operate() {
System.out.println("operation2");
}
}
//使用了某种策略的类。
class Context {
private Strategy strategy;
public Context(Strategy strategy) {
this.strategy = strategy;
}
public void executeStrategy() {
strategy.operate();
}
}
本文标题:java 策略模式
本文链接:https://www.haomeiwen.com/subject/yjxfbftx.html
网友评论