【设计模式】策略模式
来源:互联网 发布:贵州广电网络公司地址 编辑:程序博客网 时间:2024/06/06 02:07
使用频率:★★★★☆
什么是策略模式
对象的行为,在不同的环境下,有不同的实现;
比如人的上班行为,在不同的环境下,可以选择走路上班或者开车上班,由客户端根据情况决定采用何种策略;
补充说明
符合“开闭原则”,可以在不修改原有代码的基础上替换、添加新的策略;
不同的策略可以相互替换;
客户端自己决定在什么情况下使用什么具体策略角色;
与状态模式区别:使用策略模式时,客户端手动选择策略,使用状态模式时,其行为是根据状态是自动切换的。
角色
抽象策略
具体策略
环境
例子,JAVA实现
例子描述:人上班,使用步行或者开车上班;
策略:步行上班、开车上班...
关系图
抽象策略接口
package com.pichen.dp.behavioralpattern.strategy;public interface IStrategy { public void execute();}
具体策略
package com.pichen.dp.behavioralpattern.strategy;public class DriveStrategy implements IStrategy{ /** * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute() */ @Override public void execute() { System.out.println("driving。。。"); }}
package com.pichen.dp.behavioralpattern.strategy;public class WalkStrategy implements IStrategy{ /** * @see com.pichen.dp.behavioralpattern.strategy.IStrategy#execute() */ @Override public void execute() { System.out.println("walking。。。"); }}
环境
package com.pichen.dp.behavioralpattern.strategy;public class Context { IStrategy strategy; public Context(IStrategy strategy) { this.strategy = strategy; } public void execute() { this.strategy.execute(); }}
客户端
package com.pichen.dp.behavioralpattern.strategy;public class Main { public static void main(String[] args) { Context context = null; context = new Context(new WalkStrategy()); context.execute(); context = new Context(new DriveStrategy()); context.execute(); }}
结果打印
walking。。。driving。。。
JDK中的示例,Collections.sort方法
不需为新的对象修改sort()方法,你需要做的仅仅是实现你自己的Comparator接口:
Collections.sort( list, //待排序的集合 new Comparator<>(){ //具体排序策略 @Override public int compare(A a1, A a2) { return ; //具体大小判断规则 } });
@author 风一样的码农
@blog_url http://www.cnblogs.com/chenpi/
分类: 设计模式
标签: DesignPattern, JAVA
好文要顶关注我 收藏该文
0
0
«上一篇:【设计模式】迭代器模式
»下一篇:【设计模式】状态模式
»下一篇:【设计模式】状态模式
0 0
- 设计模式-策略模式
- 设计模式:策略模式
- 设计模式-策略模式
- 设计模式 - 策略模式
- 设计模式-策略模式
- 设计模式-----策略模式
- 设计模式 策略模式
- 设计模式-策略模式
- 设计模式-【策略模式】
- 设计模式-----策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 设计模式- 策略模式
- 设计模式- 策略模式
- 设计模式------策略模式
- 设计模式--策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- MSB与LSB Big Endian Little Endian
- MySQL自动重新连接
- RTMP直播应用与延时分析
- beta分布的采样或抽样(java程序)
- mysql 安装完成后 无法登录 提示密码相关错误
- 【设计模式】策略模式
- 什么是IaaS, PaaS和SaaS及其区别
- mybatis的特殊情景语句操作
- 实现一个栈, 其 Push,Pop,Min 操作的 时间复杂度 均为 O( 1 )
- Spring mvc interceptor配置拦截器
- Servlet-4
- 弄不明白抽象类和接口就回头看看
- Netty精粹之轻量级内存池技术实现原理与应用
- 文件备份替换更新批处理