运用共享技术有效地支持大量细粒度的对象。
在围棋中,棋子就是大量细粒度的对象。其属性有内在的,比如颜色、形状等,也有外在的,比如在棋盘上的位置。内在的属性是可以共享的,区分在于外在属性。因此,可以这样设计,只需定义两个棋子的对象,一颗黑棋和一颗白棋,这两个对象含棋子的内在属性;棋子的外在属性,即在棋盘上的位置可以提取出来,存放在单独的容器中。相比之前的方案,现在容器中仅仅存放了位置属性,而原来则是棋子对象。显然,现在的方案大大减少了对于空间的需求。

#include<iostream>
#include<string>
#include<list>
#include<vector>
using namespace std;

//棋子颜色
enum PieceColor { BLACK, WHITE };
//棋子位置
struct PiecePos
{
	int x;
	int y;
	PiecePos(int a, int b) : x(a), y(b) {}
};
//棋子定义
class Piece
{
protected:
	PieceColor m_color; //颜色
public:
	Piece(PieceColor color) : m_color(color) {}
	~Piece() {}
	virtual void Draw() {}
};
class BlackPiece : public Piece
{
public:
	BlackPiece(PieceColor color) : Piece(color) {}
	~BlackPiece() {}
	void Draw() { cout << "绘制一颗黑棋\n"; }
};
class WhitePiece : public Piece
{
public:
	WhitePiece(PieceColor color) : Piece(color) {}
	~WhitePiece() {}
	void Draw() { cout << "绘制一颗白棋\n"; }
};

//棋盘的定义
class PieceBoard
{
private:
	vector<PiecePos> m_vecPos; //存放棋子的位置
	Piece *m_blackPiece;       //黑棋棋子 
	Piece *m_whitePiece;       //白棋棋子
	string m_blackName;
	string m_whiteName;
public:
	PieceBoard(string black, string white) : m_blackName(black), m_whiteName(white)
	{
		m_blackPiece = NULL;
		m_whitePiece = NULL;
	}
	~PieceBoard() { delete m_blackPiece; delete m_whitePiece; }
	void SetPiece(PieceColor color, PiecePos pos)
	{
		if (color == BLACK)
		{
			if (m_blackPiece == NULL)  //只有一颗黑棋
				m_blackPiece = new BlackPiece(color);
			cout << m_blackName << "在位置(" << pos.x << ',' << pos.y << ")";
			m_blackPiece->Draw();
		}
		else
		{
			if (m_whitePiece == NULL)
				m_whitePiece = new WhitePiece(color);
			cout << m_whiteName << "在位置(" << pos.x << ',' << pos.y << ")";
			m_whitePiece->Draw();
		}
		m_vecPos.push_back(pos);
	}
};

int main()
{
	PieceBoard pieceBoard("A", "B");
	pieceBoard.SetPiece(BLACK, PiecePos(4, 4));
	pieceBoard.SetPiece(WHITE, PiecePos(4, 16));
	pieceBoard.SetPiece(BLACK, PiecePos(16, 4));
	pieceBoard.SetPiece(WHITE, PiecePos(16, 16));

	getchar();
	return 0;
}

在这里插入图片描述

Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐