设计模式--策略模式

介绍

在策略模式(Strategy Pattern)中,一个类的行为或其算法可以在运行时更改。这种类型的设计模式属于行为型模式。

主要解决:在有多种算法相似的情况下,使用 if...else 所带来的复杂和难以维护。

实现

  1. //抽象接口  
  2. class ReplaceAlgorithm  
  3. {  
  4. public:  
  5.     virtual void Replace() = 0;  
  6. };  
  7. //三种具体的替换算法  
  8. class LRU_ReplaceAlgorithm : public ReplaceAlgorithm  
  9. {  
  10. public:  
  11.     void Replace() { cout<<"Least Recently Used replace algorithm"<<endl; }  
  12. };  
  13.   
  14. class FIFO_ReplaceAlgorithm : public ReplaceAlgorithm  
  15. {  
  16. public:  
  17.     void Replace() { cout<<"First in First out replace algorithm"<<endl; }  
  18. };  
  19. class Random_ReplaceAlgorithm: public ReplaceAlgorithm  
  20. {  
  21. public:  
  22.     void Replace() { cout<<"Random replace algorithm"<<endl; }  
  23. };  

  接着给出Cache的定义,这里很关键,Cache的实现方式直接影响了客户的使用方式,其关键在于如何指定替换算法。

         方式一:直接通过参数指定,传入一个特定算法的指针。

[cpp]  view plain  copy
 print ?
  1. //Cache需要用到替换算法  
  2. class Cache  
  3. {  
  4. private:  
  5.     ReplaceAlgorithm *m_ra;  
  6. public:  
  7.     Cache(ReplaceAlgorithm *ra) { m_ra = ra; }  
  8.     ~Cache() { delete m_ra; }  
  9.     void Replace() { m_ra->Replace(); }  
  10. };  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值