享元模式——C++实现
问题描述:
设计一个围棋软件,在系统中只存在一个白棋对象和一个黑棋对象,但是它们可以在棋盘的不同位置显示多次。
类图:
代码:
#include<iostream> using namespace std; #include<String> #include<vector> //棋子颜色 enum ChessColor { BLACK, WHITE }; //棋子位置 struct Coordinates { int x; int y; Coordinates(int a, int b) : x(a), y(b) {} }; //棋子定义 class Chess { protected: ChessColor m_color; //颜色 public: Chess(ChessColor color) : m_color(color) {} ~Chess() {} virtual void Draw() {} }; class BlackChess : public Chess { public: BlackChess(ChessColor color) : Chess(color) {} ~BlackChess() {} void Draw() { cout << "绘制一颗黑棋"<<endl; } }; class WhiteChess : public Chess { public: WhiteChess(ChessColor color) : Chess(color) {} ~WhiteChess() {} void Draw() { cout << "绘制一颗白棋"<<endl; } }; class ChessFactory { private: vector<Coordinates> m_vecPos; //存放棋子的位置 Chess *m_blackChess; //黑棋棋子 Chess *m_whiteChess; //白棋棋子 string m_blackName; string m_whiteName; public: ChessFactory(string black, string white) : m_blackName(black), m_whiteName(white) { m_blackChess = NULL; m_whiteChess = NULL; } ~ChessFactory() { delete m_blackChess; delete m_whiteChess; } void setChess(ChessColor color, Coordinates pos) { if (color == BLACK) { if (m_blackChess == NULL) m_blackChess = new BlackChess(color); cout << m_blackName << "在位置:" << pos.x << ',' << pos.y ; m_blackChess->Draw(); } else { if (m_whiteChess == NULL) m_whiteChess = new WhiteChess(color); cout << m_whiteName << "的位置:" << pos.x << ',' << pos.y ; m_whiteChess->Draw(); } m_vecPos.push_back(pos); } }; //主函数 int main() { ChessFactory chessFactory("甲", "乙"); chessFactory.setChess(BLACK, Coordinates(2, 3)); chessFactory.setChess(WHITE, Coordinates(3, 6)); chessFactory.setChess(BLACK, Coordinates(5, 2)); chessFactory.setChess(WHITE, Coordinates(4, 3)); chessFactory.setChess(BLACK, Coordinates(3, 7)); }
运行截图: