策略模式--条条大路通罗马(行为模式07)
来源:互联网 发布:js刷新页面 编辑:程序博客网 时间:2024/06/14 06:49
什么是策略模式
策略模式定义了一系列封装好的算法,使他们可以相互替换。
策略模式让算法独立于使用他的客户端独立变化。
策略模式的适用场景
同一种问题有多重处理方式,仅仅在具体实现有差别
需要安全的封装同一类型的操作
实现同一抽象有多个子类,而又需要适用分支操作选择具体子类时
策略模式用例
我们从出发地到目的地可以选择坐公交车,也可以选择打的,公交车比较便宜实惠,打的比较贵但是快且舒适,选择哪一种方式都能实现目的,但是根据实际情况,比如时间紧迫怕堵车可以选择摩的,不怕挤可以选择公交,想要舒适的环境可以多花点钱打的等。
UML用例图
IPrice接口:
public interface IPrice { int calculatePrice(int distance);}
BusStrategy:
public class BusStrategy implements IPrice { @Override public int calculatePrice(int distance) { // 公交车票价,起步价1元,3公里外每公里加一元 int total = distance - 3; int mPrice = total + 1; return distance>0?mPrice:1; }}
CarStrategy:
public class CarStrategy implements IPrice { @Override public int calculatePrice(int distance) { // 出租车票价,起步价5元,3公里外每公里加3元 int total = distance - 3; int mPrice = total*3 + 5; return distance>0?mPrice:5; }}
测试类:
public class Test { BusStrategy bs; CarStrategy cs; public static void main(String[] args) { //公交车 Test test = new Test(); test.setBusStrategy(new BusStrategy()); System.out.println("公交车价格:"+test.calculateBusPrice(10)+" 元"); //出租车 Test test2 = new Test(); test2.setCarStrategy(new CarStrategy()); System.out.println("出租车价格:"+test2.calculateCarPrice(10)+" 元"); } public void setBusStrategy(BusStrategy bs){ this.bs = bs; } public int calculateBusPrice(int distance){ return bs.calculatePrice(distance); } public void setCarStrategy(CarStrategy cs){ this.cs = cs; } public int calculateCarPrice(int distance){ return cs.calculatePrice(distance); }}
测试结果:
公交车价格:8 元出租车价格:26 元
策略模式总结:
策略模式主要用来分离算法步骤,比如这个我们把公交和出租车分开来计算,解耦操作。
优点:结构清晰,使用简单。耦合度低,扩展方便。操作封装彻底,数据安全。
缺点:随着策略增多,子类更多,比如我们要加入火车、飞机、轮船等等交通工具。
阅读全文
0 0
- 策略模式--条条大路通罗马(行为模式07)
- 行为模式-策略模式
- 行为模式-策略模式
- 策略模式 - 行为模式
- 行为模式->策略模式
- 行为模式:Strategy(策略)
- 策略模式(行为型)
- 策略模式(行为型)
- 策略模式(行为型)
- 行为型模式-----策略模式(Strategy)
- 策略模式(行为型模式)
- (行为型模式七)策略模式
- Strategy模式(策略模式 行为型)
- 策略模式(行为类模式)
- 行为型-策略模式
- 搭配行为--策略模式
- 行为型模式-策略
- 设计模式-行为-策略
- 83 C语言带参数宏定义
- Android资源
- 红黑树的模拟实现
- 二分查找
- C++泛型编程入门
- 策略模式--条条大路通罗马(行为模式07)
- Linux+ ubuntu + 阿里云 + apache WebServer WEB服务器搭建
- Android的事件处理之基于监听的事件处理
- 前端开发中关于浏览器兼容性的部分问题
- RMQ算法
- 系统设计二之实例门户网站
- 自然抠图算法:以经典的贝叶斯抠图为例(Bayesian Matting)
- leetcode283题解
- qwb去面试 思路+代码