策略模式学习
策略模式UML:
ContextType1、ContextType2在构造方法或set方法中初始化各自需要的StrategyType
策略模式代码
/** * 策略接口 */ public interface Strategy { public void strategyInterfaceMethod(); } /** * 具体策略A */ public class StrategyTypeA implements Strategy { @Override public void strategyInterfaceMethod() { // todo someting } } /** * 具体策略B */ public class StrategyTypeB implements Strategy { @Override public void strategyInterfaceMethod() { // todo someting } } /** * 上下文抽象类 * 我理解的这个类的作用是:负责策略与用户(使用者)的连接,也是策略模式的入口 */ public AbstractClass Context { //持有一个具体策略的对象 private Strategy strategy; /** * 构造函数,传入一个具体策略对象 * @param strategy */ public Context(Strategy strategy){ this.strategy = strategy; } /** * 策略方法 */ public void contextMethod(){ strategy.strategyInterfaceMethod(); } } /** * 具体环境类 */ public Class ContextType1 extends Context{ public void contextMethod(){ strategy.strategyInterfaceMethod(); // todo something } }
应用场景: 多个用户购买不同型号电脑
public class Client { public static void main(String[] args) { // 客户需要定制自己需要的策略 // 策略1--购买戴尔电脑 Strategy dell = new StrategyTypeA(); dell.setCPU("AMD"); dell.setScreen("LGD"); // 策略2 Strategy macbook = new StrategyTypeB(); macbook.setCPU("Intel"); macbook.setScreen("sansung"); // 购买的是dell电脑 // 用户将自己需要的策略(电脑配置)交给商家 ContextType1 customer1 = new ContextType1(dell); // buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeA.strategyInterfaceMethod(); customer1.buyComputer(); // 购买的是macbook ContextType2 customer2 = new ContextType2(macbook); // buyComputer方法中的strategy.strategyInterfaceMethod(); = StrategyTypeB.strategyInterfaceMethod(); customer2.buyComputer(); } }
相关推荐
tracy 2020-08-31
natloc 2020-07-18
Codeeror 2020-06-28
baike 2020-06-14
Ingram 2020-06-04
yishujixiaoxiao 2020-06-03
走在IT的路上 2020-05-01
txlCandy 2020-04-20
清溪算法君老号 2020-04-14
wuxiaosi0 2020-02-22
shawsun 2020-02-14
spb 2020-02-14
xcguoyu 2020-02-14
wangxiaohua 2014-05-29
mbcsdn 2019-12-20
ustbfym 2019-12-01