一、策略模式简介
1、定义
2、使用场景
3、优缺点
3、UML类图
二、策略模式实现
1、策略角色
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:28
*/
public abstract class Strategy {
// 算法方法
public abstract void algorithmInterface();
}
2、具体策略角色
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:31
*/
public class ConcreteStrategyA extends Strategy {
@Override
public void algorithmInterface() {
System.out.println("这是算法A");
}
}
3、 Context上下文
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:32
*/
public class Context {
Strategy strategy;
public Context (Strategy strategy) {
// 初始化时,传入具体的策略对象
this.strategy = strategy;
}
// 上下文接口
public void ContextInterface() {
// 根据具体的策略对象,调用就其算法的方法
strategy.algorithmInterface();
}
}
4、Client客户端
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:36
*/
public class Client_Strategy {
public static void main(String[] args) {
doStrategy("A");
doStrategy("B");
doStrategy("C");
}
public static void doStrategy(String options){
Context context = null;
switch (options){
case "A":
context = new Context(new ConcreteStrategyA());
context.ContextInterface();
break;
case "B":
context = new Context(new ConcreteStrategyB());
context.ContextInterface();
break;
case "C":
context = new Context(new ConcreteStrategyC());
context.ContextInterface();
break;
}
}
}
运行结果如下:
5、分析
三、策略模式与简单工厂结合
1、改造后的context
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:32
*/
public class Context_Factory {
Strategy strategy = null;
public Context_Factory(String options) {
// 初始化时,根据客户端不同的选择,实例化具体的策略对象
switch (options){
case "A":
strategy = new ConcreteStrategyA();
break;
case "B":
strategy = new ConcreteStrategyB();
break;
case "C":
strategy = new ConcreteStrategyC();
break;
}
}
// 上下文接口
public void ContextInterface() {
// 根据具体的策略对象,调用就其算法的方法
strategy.algorithmInterface();
}
}
2、改造后的客户端
package com.mfc.design.策略模式;
/**
* @author MouFangCai
* @date 2019/10/11 11:36
*/
public class Client_Strategy_Factory {
public static void main(String[] args) {
String options = "A";
Context_Factory a = new Context_Factory(options);
a.ContextInterface();
}
}