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 }
时间: 2024-11-10 06:13:02