享元模式

 

#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);
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值