设计模式--策略模式
来源:互联网 发布:应力分析软件 编辑:程序博客网 时间:2024/06/05 02:43
介绍
在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。
主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。
实现
- //抽象接口
- class ReplaceAlgorithm
- {
- public:
- virtual void Replace() = 0;
- };
- //三种具体的替换算法
- class LRU_ReplaceAlgorithm : public ReplaceAlgorithm
- {
- public:
- void Replace() { cout<<"Least Recently Used replace algorithm"<<endl; }
- };
- class FIFO_ReplaceAlgorithm : public ReplaceAlgorithm
- {
- public:
- void Replace() { cout<<"First in First out replace algorithm"<<endl; }
- };
- class Random_ReplaceAlgorithm: public ReplaceAlgorithm
- {
- public:
- void Replace() { cout<<"Random replace algorithm"<<endl; }
- };
接着给出Cache的定义,这里很关键,Cache的实现方式直接影响了客户的使用方式,其关键在于如何指定替换算法。
方式一:直接通过参数指定,传入一个特定算法的指针。
- //Cache需要用到替换算法
- class Cache
- {
- private:
- ReplaceAlgorithm *m_ra;
- public:
- Cache(ReplaceAlgorithm *ra) { m_ra = ra; }
- ~Cache() { delete m_ra; }
- void Replace() { m_ra->Replace(); }
- };
0 0
- 设计模式-策略模式
- 设计模式:策略模式
- 设计模式-策略模式
- 设计模式 - 策略模式
- 设计模式-策略模式
- 设计模式-----策略模式
- 设计模式 策略模式
- 设计模式-策略模式
- 设计模式-【策略模式】
- 设计模式-----策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 设计模式- 策略模式
- 设计模式- 策略模式
- 设计模式------策略模式
- 设计模式--策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 数据分析能力的8个等级
- iOS 图片捏合放大缩小 点击放大缩小
- Inno Setup入门(十二)——Pascal脚本(1)
- RHEL 6.7 使用multipathd reload命 令有导致DB实例Crash风险,特发Alert提醒,请关注!
- Java 容器(四) Map
- 设计模式--策略模式
- Android自定义View解析之视图状态及视图重绘(二)
- 定时器实现定时功能
- 海思3518e mpp2/sample/venc makefile简析
- opencv函数操作对象的一致性问题
- Android Volley完全解析(一),初识Volley的基本用法
- mybatis 之 generator插件使用 集成到了eclipse 自动生成实体,example,mapper
- iOS获取当前年、月、日等信息
- linux下查看和添加PATH环境变量