码迷,mamicode.com
首页 > 其他好文 > 详细

1、策略模式(Strategy)

时间:2015-07-29 12:05:15      阅读:99      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!