设计模式:2策略模式
来源:互联网 发布:少儿英语培训推荐 知乎 编辑:程序博客网 时间:2024/06/06 09:00
策略模式:
制定一系列的算法,然后封装起来,使他们可以相互替换。本模式使得算法可以独立于使用它的客户而变化,算法完成的功能一样。只是各自实现存在差异。
类的划分是为了封装,分类基础是抽象,具有相同属性和功能的对象的抽象几何才是类
实例:
Cache替换算法,有先进先出,LRU,随机
main.cpp
#include <iostream>#include <stdlib.h>#include "Cache.h"#include "ReplaceAlgorithm.h"void process(){//Cache<LRU_ReplaceAlgorithm> cache;//模板实参//cache.replace();Cache<LRU_ReplaceAlgorithm> cache(FIFO);cache.replace2();}int main(int argc,char* argv[]){process();system("pause");return 0;}
Cache.h
#ifndef CACHE_H#define CACHE_H#include <memory>#include "ReplaceAlgorithm.h"enum RA_TYPE{LRU , FIFO , RANDOM};//标签template<class RA>class Cache{public:/*Cache(void);~Cache(void);void replace();*///传入标签,客户只需要知道算法的相应标签即可,不需要知道算法的具体定义。Cache(enum RA_TYPE ra){if(ra == LRU){_ptrRA.reset(new LRU_ReplaceAlgorithm());}else if(ra == FIFO){_ptrRA.reset(new FIFO_ReplaceAlgorithm());}else if(ra == RANDOM){_ptrRA.reset(new Random_ReplaceAlgorithm());}else{_ptrRA = NULL;}}Cache(void){}~Cache(void){}void replace(){_ra.replace();}void replace2(){_ptrRA->replace();}private:RA _ra;std::shared_ptr<ReplaceAlgorithm> _ptrRA;};#endif
ReplaceAlgorithm.h
#ifndef REPLACEALGORITHM_H#define REPLACEALGORITHM_Hclass ReplaceAlgorithm{public:ReplaceAlgorithm(void);virtual ~ReplaceAlgorithm(void);virtual void replace() = 0;};class FIFO_ReplaceAlgorithm : public ReplaceAlgorithm{public:FIFO_ReplaceAlgorithm(void);~FIFO_ReplaceAlgorithm(void);void replace();};class LRU_ReplaceAlgorithm : public ReplaceAlgorithm{public:LRU_ReplaceAlgorithm(void);~LRU_ReplaceAlgorithm(void);void replace();};class Random_ReplaceAlgorithm : public ReplaceAlgorithm{public:Random_ReplaceAlgorithm(void);~Random_ReplaceAlgorithm(void);void replace();};#endif
ReplaceAlgorithm.cpp
#include "ReplaceAlgorithm.h"#include <iostream>using namespace std;ReplaceAlgorithm::ReplaceAlgorithm(void){}ReplaceAlgorithm::~ReplaceAlgorithm(void){}FIFO_ReplaceAlgorithm::FIFO_ReplaceAlgorithm(){}FIFO_ReplaceAlgorithm::~FIFO_ReplaceAlgorithm(){}void FIFO_ReplaceAlgorithm::replace(){cout <<"先进先出算法" << endl;}LRU_ReplaceAlgorithm::LRU_ReplaceAlgorithm(){}LRU_ReplaceAlgorithm::~LRU_ReplaceAlgorithm(){}void LRU_ReplaceAlgorithm::replace(){cout <<"最近最少使用算法" << endl;}Random_ReplaceAlgorithm::Random_ReplaceAlgorithm(){}Random_ReplaceAlgorithm::~Random_ReplaceAlgorithm(){}void Random_ReplaceAlgorithm::replace(){cout <<"随机算法" << endl;}
0 0
- 设计模式:2策略模式
- 设计模式【2】:策略模式
- 设计模式:2)策略设计模式
- 设计模式-策略模式
- 设计模式:策略模式
- 设计模式-策略模式
- 设计模式 - 策略模式
- 设计模式-策略模式
- 设计模式-----策略模式
- 设计模式 策略模式
- 设计模式-策略模式
- 设计模式-【策略模式】
- 设计模式-----策略模式
- 设计模式-策略模式
- 设计模式--策略模式
- 设计模式- 策略模式
- 设计模式- 策略模式
- 设计模式------策略模式
- 黑马程序员——ios学习笔记 OC Foundation—NSArray&NSDictionary
- !HDU 5371 最长双回文串(多校7)-卡时间-(manacher+排序+set+lower_bound())
- 给出两个年月日,计算出天数差。
- 设计模式:1.3 抽象工厂模式
- 黑马程序员--Java基础--集合(一)
- 设计模式:2策略模式
- ACM 2015 中国赛区时间
- Chromium的Render进程启动过程分析
- 设计模式: 3 单一职责原则
- 设计模式: 4开放封闭原则
- SQL语法之查询语句
- HDU 3577 Fast Arrangement
- Android中自定义属性(attrs.xml,TypedArray的使用)
- 设计模式:5 依赖倒转原则