#include <iostream.h>
#include <vector>
using namespace std;
//享元模式
//以围棋为例 棋子和棋盘是状态稳定的 视为内部状态 棋子为大粒度对象
//棋子相对于棋盘的位置是不稳定的状态 视为外部状态
//棋盘在整个围棋中,从常态看,其上有棋子和相对位置,但它不用在意有多少棋子
//棋盘只需要知道自己身上只有两种颜色和这两种颜色出现的不同位置
//于是大量的棋子对象就可以简化成两种颜色而位置信息对于棋子来说,完全可以不用知道
//位置就是棋子外部状态,而这个状态可以有棋子外的其它对象记录并控制
//若使棋子本身知道自己的颜色和位置,那么每个棋子都得实例化
//361个实例和2个实例相比,粒度大很多
class status //一般状态 无意义
{
public:
status(){}
virtual ~status(){}
};
class position //棋子相对于棋盘的位置
{
protected:
int x , y ; //位置
public:
position():x(0),y(0){}
virtual ~position(){}
public:
void SetPos(int x , int y)
{
this->x = x;
this->y = y;
}
int GetXPos()
{
return this->x;
}
int GetYPos()
{
return this->y;
}
};
class Chessman : public status //棋子
{
protected:
int white;
int black;
public:
Chessman():white(0),black(0){}
virtual ~Chessman(){}
public:
void SetColor(int a)
{
if(1 == a)
white = 1;
else
black = 1;
}
int GetW()
{
return white;
}
int GetB()
{
return black;
}
};
class Chessboard : public status //棋盘
{
private:
vector<position> m_pos; //棋盘是棋子的外部对象于是就由棋盘记录棋子的位置
Chessman chess; //棋子聚合到棋盘内 是个对外在棋子对象的装载器
public:
Chessboard(){};
virtual ~Chessboard(){};
public:
void SetChessman(Chessman chess)
{
this->chess = chess;
}
void SetChessmanPos(position pos) //存储棋子相对于棋盘的位置
{
if(1 == this->chess.GetW())
{
m_pos.push_back(pos);
cout << "设置白子位于" << m_pos.back().GetXPos() << " " << m_pos.back().GetYPos() << endl;
}
if(1 == this->chess.GetB())
{
m_pos.push_back(pos);
cout << "设置黑子位于" << m_pos.back().GetXPos() << " " << m_pos.back().GetYPos() << endl;
}
}
};
void main()
{
Chessman Wchess; //白子
Chessman Bchess; //黑子
Chessboard board; //棋盘
Wchess.SetColor(1);
Bchess.SetColor(0);
position pos;
pos.SetPos(1 , 1);
board.SetChessman(Wchess);
board.SetChessmanPos(pos);
pos.SetPos(1 , 2);
board.SetChessman(Bchess);
board.SetChessmanPos(pos);
pos.SetPos(2 , 1);
board.SetChessman(Wchess);
board.SetChessmanPos(pos);
pos.SetPos(2 , 2);
board.SetChessman(Bchess);
board.SetChessmanPos(pos);
}