策略模式
来源:互联网 发布:双色球选红球算法 编辑:程序博客网 时间:2024/05/29 17:57
策略模式主要用来分离算法, 在相同的行为抽象下有不同的具体实现策略. 这个模式很好的演示了开闭原则, 也就是定义抽象, 注入不同的实现, 从而达到很好的可扩展性.
优点:
1. 结构清晰明了, 使用简单直观;
2. 耦合度相对而言较低, 扩展方便;
3. 操作封装也更为彻底, 数据更为安全;
缺点:
随着策略的增加, 子类也会变得繁多;
mvp引用了策略模式的思想:
需求:
选择交通方式多, 目前有公交和地铁交通方式, 以后可能还会增加其他交通方式, 每种交通方式的价格与公里的关系都不同. 用代码完成这个需求, 如果不知道策略模式的情况下, 写的代码很可能想下面代码:
public class CalculateTest { /** 0:公交, 1:地铁 */ public int mTrafficMode; public static void main(String[] args) { CalculateTest calculateTest = new CalculateTest(); calculateTest.calculatePrice(10, 0); } public int calculatePrice(int km, int trafficMode) { if (trafficMode == 0) { if (km < 5) { return 2; } else if (km < 6) { return 3; } else if (km < 7) { return 4; } return 5; } else if (trafficMode == 1) { if (km < 5) { return 3; } else if (km < 6) { return 4; } else if (km < 7) { return 5; } return 6; } return 0; }}
上面代码最终会导致CalculateTest中的逻辑代码非常繁杂凌乱, 如果是在Android中, 就会导致mvp的view中的逻辑代码非常多, 降低了代码的可复用性, 不利于扩展.
如果采用策略模式:
public interface CalculateStrategy { int calculatePrice(int km);}public class BusStrategy implements CalculateStrategy { public int calculatePrice(int km) { if (km < 5) { return 2; } else if (km < 6) { return 3; } else if (km < 7) { return 4; } return 5; }}public class SubmwayStrategy implements CalculateStrategy { public int calculatePrice(int km) { if (km < 5) { return 3; } else if (km < 6) { return 4; } else if (km < 7) { return 5; } return 6; }}public class StrategyTest { public CalculateStrategy mStrategy; public static void main(String[] args) { StrategyTest strategyTest = new StrategyTest(); strategyTest.setStrategy(new BusStrategy()); int price = strategyTest.calculatePrice(10); System.out.println("price:" + price); } public void setStrategy(CalculateStrategy strategy) { mStrategy = strategy; } public int calculatePrice(int km) { return mStrategy.calculatePrice(km); }}
只需要在StrategyTest中暴露一个setStrategy接口即可;
0 0
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- RFDBs 一款轻量级的文件型Key-Value大容量存储的数据库
- 将两个或多个应用放到同一个进程的方法
- hdu 2896 病毒侵袭 AC自动机入门题
- Java自定义注解
- Ubuntu16.04安装Anaconda2和Anaconda3
- 策略模式
- node-webkit制作桌面应用
- libevent_server 服务器程序详细注释
- Integer和int——Java包装器
- w未搞定的算法总结
- java-final关键字作用
- 基于Spring Boot和Cloud Foundry实现微服务架构学习(2017227更新)
- 关于SVD分解
- C语言