设计模式--策略模式

来源:互联网 发布:应力分析软件 编辑:程序博客网 时间:2024/06/05 02:43

介绍

在策略模式(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
原创粉丝点击