软件设计⑩③|享元模式
一、效果
二、类图
三、效果
1 #include <iostream> 2 #include <map> 3 #include <vector> 4 using namespace std; 5 6 typedef enum PieceColorTag 7 { 8 BLACK, 9 WHITE 10 }PIECECOLOR; 11 12 class CPiece 13 { 14 public: 15 CPiece(PIECECOLOR color) : color(color) {} 16 PIECECOLOR GetColor() { return color; } 17 protected: 18 // Internal state 19 PIECECOLOR color; 20 }; 21 22 class CGomoku : public CPiece 23 { 24 public: 25 CGomoku(PIECECOLOR color) : CPiece(color) {} 26 }; 27 28 class CPieceFactory 29 { 30 public: 31 CPiece* GetPiece(PIECECOLOR color) 32 { 33 CPiece* pPiece = NULL; 34 if (m_vecPiece.empty()) 35 { 36 pPiece = new CGomoku(color); 37 m_vecPiece.push_back(pPiece); 38 } 39 else 40 { 41 for (vector<CPiece*>::iterator it = m_vecPiece.begin(); it != m_vecPiece.end(); ++it) 42 { 43 if ((*it)->GetColor() == color) 44 { 45 pPiece = *it; 46 break; 47 } 48 } 49 if (pPiece == NULL) 50 { 51 pPiece = new CGomoku(color); 52 m_vecPiece.push_back(pPiece); 53 } 54 } 55 return pPiece; 56 } 57 58 ~CPieceFactory() 59 { 60 for (vector<CPiece*>::iterator it = m_vecPiece.begin(); it != m_vecPiece.end(); ++it) 61 { 62 if (*it != NULL) 63 { 64 delete* it; 65 *it = NULL; 66 } 67 } 68 } 69 70 private: 71 vector<CPiece*> m_vecPiece; 72 }; 73 74 class CChessboard 75 { 76 public: 77 void Draw(CPiece* piece) 78 { 79 if (piece->GetColor()) 80 { 81 cout << "棋子颜色:白棋" << endl; 82 } 83 else 84 { 85 cout << "棋子颜色:黑棋" << endl; 86 } 87 } 88 }; 89 90 int main() 91 { 92 CPieceFactory* pPieceFactory = new CPieceFactory(); 93 CChessboard* pCheseboard = new CChessboard(); 94 95 CPiece* pPiece = pPieceFactory->GetPiece(WHITE); 96 pCheseboard->Draw(pPiece); 97 98 pPiece = pPieceFactory->GetPiece(BLACK); 99 pCheseboard->Draw(pPiece); 100 101 pPiece = pPieceFactory->GetPiece(WHITE); 102 pCheseboard->Draw(pPiece); 103 104 pPiece = pPieceFactory->GetPiece(BLACK); 105 pCheseboard->Draw(pPiece); 106 }