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

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

策略模式就是将多种算法类进行封装,每个算法类都继承于一个基类A,然后重写一个新类B,在这个新类里定义一个基类A的对象,然后在新类B的构造函数中对基类A的对象进行赋值,这种方法需要对B的构造函数传参数,如果需要不传参数,则可以写成模板的形式,以下是代码:

#include <iostream>

using namespace std;

class ReplaceAlgorithm
{
public:
	ReplaceAlgorithm()
	{
	}
	~ReplaceAlgorithm()
	{
	}
public:
	virtual void Replace() = 0;
	
};

//three replace algorithm
class LRU_ReplaceAlgorithm:public ReplaceAlgorithm
{
public:
	void Replace()
	{
		cout<<"Least Recently Used replace algorithm"<<endl;
	}
};

class FIFO_ReplaceAlogrithm:public ReplaceAlgorithm
{
public:
	void Replace()
	{
		cout<<"First in Fist out replace algorithm"<<endl;
	}
};

class Random_ReplaceAlgorithm:public ReplaceAlgorithm{
public:
	void Replace()
	{
		cout<<"Random replace algorithm"<<endl;
	}
};

/*
enum RA {LRU, FIFO, RANDOM};

class Cache
{
private:
	ReplaceAlgorithm * m_ra;
public:
	Cache(enum RA ra)
	{
		if(ra == LRU)
		{
			m_ra = new LRU_ReplaceAlgorithm();
		}
		else if(ra == FIFO)
		{
			m_ra = new FIFO_ReplaceAlogrithm();
		}
		else if(ra == RANDOM)
		{
			m_ra = new Random_ReplaceAlgorithm();
		}
		else
			m_ra = NULL;
	}
	~Cache()
	{
		delete m_ra;
	}
	void Replace()
	{
		m_ra->Replace();
	}
};
*/
template <class RA>
class Cache
{
private:
	RA m_ra;
public:
	Cache()
	{

	}
	~Cache()
	{

	}
	void Replace()
	{
		m_ra.Replace();
	}
};

int main()
{
	cout<<"start to test"<<endl;
	//Cache cache(LRU);
	Cache<Random_ReplaceAlgorithm> cache;
	cache.Replace();
	return 0;
}

猜你喜欢

转载自blog.csdn.net/jiangyingfeng/article/details/81280259