首页 > 其他 > 详细

1、策略模式(Strategy)

时间:2015-07-29 12:02:10      阅读:145      评论:0      收藏:0      [点我收藏+]
 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 };  

 

 1 //Cache需要用到替换算法  
 2 enum RA {LRU, FIFO, RANDOM}; //标签  
 3 class Cache  
 4 {  
 5 private:  
 6     ReplaceAlgorithm *m_ra;  
 7 public:  
 8     Cache(enum RA ra)   
 9     {   
10         if(ra == LRU)  
11             m_ra = new LRU_ReplaceAlgorithm();  
12         else if(ra == FIFO)  
13             m_ra = new FIFO_ReplaceAlgorithm();  
14         else if(ra == RANDOM)  
15             m_ra = new Random_ReplaceAlgorithm();  
16         else   
17             m_ra = NULL;  
18     }  
19     ~Cache() { delete m_ra; }  
20     void Replace() { m_ra->Replace(); }  
21 };  

 

1 int main()  
2 {  
3     Cache cache(LRU); //指定标签即可  
4     cache.Replace();  
5     return 0;  
6 }  

 

1、策略模式(Strategy)

原文:http://www.cnblogs.com/leiqiu/p/4685243.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!