7. 策略模式
来源:互联网 发布:军工复合体 知乎 编辑:程序博客网 时间:2024/06/06 08:49
一. 策略模式的定义
定义一组算法, 然后将这些算法封装起来简化外部调用 . 每个算法之间可以互相替换
策略模式的成员:
1. Context : 封装算法 , 屏蔽上层模块对算法的直接访问 , 封装调用算法时可能存在的变化
2. Strategy接口 : 对所有算法的抽象 , 以实现每种算法可以花香替换的目的
3. ConcreteStrategy : 具体的每条算法
二. 策略模式的扩展 : 策略枚举
策略枚举不再使用子类实现具体算法, 而是把Strategy接口写成枚举对象来防止子类膨胀和策略的对外暴露
/** * 策略枚举类 */public enum Caculator { Add("+"){ @Override public int exec(int a,int b) { return a+b; } }, Sub("-"){ @Override public int exec(int a,int b) { return a-b; } }; String operator = ""; private Caculator(String operator){ this.operator = operator; } public String getOperator() { return operator; } public abstract int exec(int a,int b);}
/** * 调用 */public class Main { public static void main(String[] args) { int exec = Caculator.Add.exec(1, 2); System.out.println(exec); }}
0 0
- 7. 策略模式
- 7.php策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 策略模式
- 欢迎使用CSDN-markdown编辑器
- COM组件设计与应用(二)——GUID和接口
- mysql DQL exercise
- Memcached学习笔记
- iOS判断是否联网
- 7. 策略模式
- Swift开发IOS-UIActivityIndicatorView
- Spring@Autowired注解与自动装配
- Windows上面编译pcre的步骤
- 牛顿下降法和梯度下降法(最速下降法)的速度的比较
- [那些年踩过的坑]Android5.0 新控件的一些注意点(持续更新
- iOS开发日记
- Codeforces Round #338 (Div. 2)
- linux中终端复用工具screen的介绍