改动的只有Context类和客户端类:
/**
* 工厂模式与策略模式相结合
*/
public class Context {
private Strategy strategy;
/***
* 这里不再传入具体的策略对象 而是传入要操作的策略标志
* 创建实例的过程 由客户端到了Context
* @param type
*/
public Context(String type) {
switch (type) {
case "A":
strategy = new ConcreteStrategyA();
break;
case "B":
strategy = new ConcreteStrategyB();
break;
case "C":
strategy = new ConcreteStrategyC();
break;
}
}
/**
* 根据具体的策略对象 调用其算法
*/
public void ContextInterface() {
// 这里可以Return计算结果给客户端
strategy.AlgorithmInterface();
}
}
public class Main {
public static void main(String[] args) {
Context context;
context = new Context("A");
context.ContextInterface();
context = new Context("B");
context.ContextInterface();
context = new Context("C");
context.ContextInterface();
}
}