享元模式(19)

享元模式

运用共享技术有效地支持大量细粒度的对象。
享元模式(19)_第1张图片

#include
#include
#include
#include
using namespace std;
enum COLOR{RED , BLACK};
//记录名字和坐标
typedef struct NODE
{
	int x;
	int y;
	string name;
}NODE;

class PIECE
{
private:
	COLOR m_color;
public:
	PIECE(COLOR p_color):m_color(p_color){}
	~PIECE(){}
	virtual void  DRAW(){}

};

class REDPIECE:public PIECE
{
public:
	REDPIECE(COLOR p_color):PIECE(p_color){}
	virtual void  DRAW(){cout<<"绘制一颗红棋子"<<endl;}
};

class BLACKPIECE:public PIECE
{
public:
	BLACKPIECE(COLOR p_color):PIECE(p_color){}
	virtual void  DRAW(){cout<<"绘制一颗黑棋子"<<endl;}
};

//棋盘
class BOARD
{
private:
	list<NODE> m_ls;
	PIECE*m_redpiece;
	PIECE*m_blackpiece;
public:
	BOARD()
	{
		m_redpiece=NULL;
		m_blackpiece=NULL;
	}

	~BOARD()
	{
		delete m_blackpiece;
		delete m_redpiece;
	}

	void SetPiece(COLOR p_color , NODE p_node)
	{
		if(p_color==RED)
		{
			if(m_redpiece == NULL)  //有点单例模式的意思
			{
				m_redpiece = new REDPIECE(p_color);	
			}
			cout<<p_node.name<<"在位置("<<p_node.x<<','<<p_node.y<<")";
			m_redpiece->DRAW();
		}
		else
		{
			if(m_redpiece == NULL)  //有点单例模式的意思
			{
				m_redpiece = new REDPIECE(p_color);	
			}
			cout<<p_node.name<<"在位置("<<p_node.x<<','<<p_node.y<<")";
			m_redpiece->DRAW();
		}
		m_ls.push_back(p_node);//这里只存放NODE的信息 ,不用存对象的信息,将会大大减少存储空间的消耗
	}

};


int main()
{
	BOARD *m_board= new BOARD();
	NODE p1;
	p1.name = "马";
	p1.x=1;
	p1.y = 2;


	NODE p2;
	p2.name = "车";
	p2.x=1;
	p2.y = 2;

	REDPIECE *m_red = new REDPIECE(RED);
	m_board->SetPiece(RED , p1);

	BLACKPIECE *m_black = new BLACKPIECE(BLACK);
	m_board->SetPiece(BLACK , p2);

	return 0;

}

你可能感兴趣的:(【C++设计模式】)