【设计模式】——策略模式(3)

mac2022-06-30  21

一、定义

策略模式就是定义一系列算法的方法,从概念上来说,所有这些算法完成的都是相同的工作,只是实现不同,他可以以相同的方式调用所有的算法,减少各种算法类与使用算法类之间的耦合。

二、框架运用

spring中ApplicationContext 实例的 getResource() 就是使用的策略模式

三、实战

1、策略接口类

public interface Strategy { void doStrategy(String str); }

2、两个策略实现类

public class StrategyA implements Strategy { @Override public void doStrategy(String str) { System.out.println("StrategyA======="+str); } } public class StrategyB implements Strategy { @Override public void doStrategy(String str) { System.out.println("StrategyB======="+str); } }

3、策略执行类

public class StategyContext { private Strategy strategy; private String str; public StategyContext(Integer type,String str) { switch (type){ case 1: this.strategy = new StrategyA(); break; case 2: this.strategy = new StrategyB(); break; default: break; } this.str = str; } public void getResult(){ strategy.doStrategy(str); } }

4、客户端

public class Client { public static void main(String[] args) { StategyContext contextA = new StategyContext(1,"策略A"); StategyContext contextB = new StategyContext(2,"策略B"); contextA.getResult(); contextB.getResult(); } }

5、结果

Connected to the target VM, address: '127.0.0.1:52126', transport: 'socket' StrategyA=======策略A StrategyB=======策略B Disconnected from the target VM, address: '127.0.0.1:52126', transport: 'socket'

 

最新回复(0)