定义:定义一系列算法,将每一个算法封装起来,并让它们可以相互替换。策略模式让算法独立于使用它的客户而变化,也称为政策模式(Policy)。
柑橘跟简单工厂模式没区别,不多写了
//抽象接口
class ReplaceAlgorithm
{
public:
virtual void Replace() = 0;
};
//三种具体的替换算法
class LRU_ReplaceAlgorithm : public ReplaceAlgorithm
{
public:
void Replace() { cout<<"Least Recently Used replace algorithm"<<endl; }
};
class FIFO_ReplaceAlgorithm : public ReplaceAlgorithm
{
public:
void Replace() { cout<<"First in First out replace algorithm"<<endl; }
};
class Random_ReplaceAlgorithm: public ReplaceAlgorithm
{
public:
void Replace() { cout<<"Random replace algorithm"<<endl; }
};
//Cache需要用到替换算法
class Cache
{
private:
ReplaceAlgorithm *m_ra;
public:
Cache(ReplaceAlgorithm *ra) { m_ra = ra; }
~Cache() { delete m_ra; }
void Replace() { m_ra->Replace(); }
};
int main()
{
Cache cache(new LRU_ReplaceAlgorithm()); //暴露了算法的定义
cache.Replace();
return 0;
}
|