C++设计模式:策略模式

时间:2021-01-31 21:58:43

策略模式:定义了算法家族,分别封装起来,然后定义一个统一的借口,算法之间可以相互替换。使用该模式可以让算法的变化不影响到使用算法的客户。

模式实现:策略模式具体实现时通常与工厂模式相结合,定义一个工厂类,来决定初始化哪个算法。

代码如下:

#include<iostream>

using namespace std;


enum RA{LRU,FIFO,RANDOM};

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_ReplaceAlgprithm :public ReplaceAlgorithm
{
public:
void Replace()
{
cout << "Random replace algorithm" << endl;
}
};

class Cache
{
private:
ReplaceAlgorithm*m_ra;
public:
Cache(RA ra)
{
if (ra == LRU)
{
m_ra = new LRU_ReplaceAlgorithm();
}
else if (ra = FIFO)
{
m_ra = new FIFO_ReplaceAlgorithm();
}
else if (ra = RANDOM)
{
m_ra = new random_ReplaceAlgprithm();
}
else
m_ra = NULL;
}
~Cache()
{
delete m_ra;
m_ra = NULL;
}

void Replace()
{
m_ra->Replace();
}
};