#include <iostream> #include <string> #include <list> #include <vector> using namespace std; enum COLOR{WHITE,BLACK}; /************************************************************************/ /* 装饰模式的作用是为对象增加属性 */ /************************************************************************/ struct PiecePos { int x; int y; PiecePos(int a,int b):x(a),y(b){} }; class Piece { public: virtual void draw(){} }; class BlackPiece:public Piece { public: virtual void draw(){cout << " set a black piece"<<endl;} }; class WhitePiece:public Piece { public: virtual void draw(){cout << " set a white piece"<<endl;} }; class PieceBoard { public: PieceBoard(string balckname,string whitename): m_whitename(whitename),m_balckname(balckname),m_blackpiece(NULL),m_whitepiece(NULL) { } void SetPiece(COLOR color,PiecePos pos) { if (color == BLACK) { if (NULL == m_blackpiece) { m_blackpiece = new BlackPiece(); } cout << m_balckname << " on the pos" << pos.x << " and " << pos.y; m_blackpiece->draw(); } else { if (NULL == m_whitepiece) { m_whitepiece = new WhitePiece(); } cout << m_whitename << " on the pos" << pos.x << " and " << pos.y; m_whitepiece->draw(); } m_vecPos.push_back(pos); } private: vector<PiecePos> m_vecPos; Piece *m_blackpiece; Piece *m_whitepiece; string m_balckname; string m_whitename; }; int main() { PieceBoard pieceboard("A","B"); pieceboard.SetPiece(WHITE,PiecePos(4,6)); pieceboard.SetPiece(BLACK,PiecePos(3,5)); pieceboard.SetPiece(WHITE,PiecePos(2,8)); pieceboard.SetPiece(BLACK,PiecePos(1,9)); return 0; }
享元模式原理:所谓享元模式,是共享一些元数据对象,例如棋盘的棋子,如果我们对每个棋子建立一个对象然后组织成一个容器,则需要很多个对象。可以只建立两个对象,一个黑子对象,一个白子对象,由棋盘共享,棋盘维护一个保存棋子位置的对象。
代码如下: