设计模式之策略模式(strategy)

策略模式原理:策略模式和简单工厂模式有点类似,只是简单工厂模式产生的是对象,策略模式产生的是根据对象产生的算法。

代码如下:

#include <iostream>
#include <string>
#include <vector>
using namespace std; enum CACHE{FIFO,LRU,RANDOM};
class ReplaceAlgorithm
{
public:
virtual void replace(){}
}; class FIFOAlgorithm:public ReplaceAlgorithm
{
public:
virtual void replace(){cout << "FIFO" <<endl;}
}; class LRUAlgorithm:public ReplaceAlgorithm
{
public:
virtual void replace(){cout << "LRU" <<endl;}
};
class RandomAlgorithm:public ReplaceAlgorithm
{
public:
virtual void replace(){cout << "Random" <<endl;}
};
class Cache
{ public:
Cache(enum CACHE cache)
{
switch (cache)
{
case FIFO:
m_preplace = new FIFOAlgorithm();
break;
case LRU :
m_preplace = new LRUAlgorithm();
case RANDOM:
m_preplace = new RandomAlgorithm();
default:
break;
}
};
void replace()
{
m_preplace->replace();
}
private:
ReplaceAlgorithm *m_preplace;
}; int main()
{
Cache cache(FIFO);
cache.replace();
return 0;
}
上一篇:store.js - 轻松实现本地存储(LocalStorage)


下一篇:windows驱动编程入门(第一个程序)