C++设计模式之享元模式

概述

想想我们编辑文档用的wps,文档里文字很多都是重复的,我们不可能为每一个出现的汉字都创建独立的空间,这样代价太大,最好的办法就是共享其中相同的部分,使得需要创建的对象降到最小,这个就是享元模式的核心,即运用共享技术有效地支持大量细粒度的对象。

 

享元对象能做到共享的关键是区分内蕴状态(Internal State)和外蕴状态(External State)。内蕴状态是存储在享元对象内部并且不会随环境改变而改变。因此内蕴状态并可以共享。

外蕴状态是随环境改变而改变的、不可以共享的状态。享元对象的外蕴状态必须由客户端保存,并在享元对象被创建之后,在需要使用的时候再传入到享元对象内部。外蕴状态与内蕴状态是相互独立的。

类图与样例

  1 // Flyweight.cpp : 定义控制台应用程序的入口点。
  2 //
  3 
  4 #include "stdafx.h"
  5 #include <iostream>
  6 #include<string>
  7 #include <map>
  8 using namespace std;
  9 
 10 class Character
 11 {
 12 public:
 13     virtual ~Character(){};
 14     virtual void SetSize(int,int) = 0;
 15     virtual void Display() = 0;
 16 protected:
 17     Character() {}
 18     char m_chSymbol;
 19     int m_nWeight;
 20     int m_nHeight;
 21 };
 22 
 23 class CharacterA:public Character
 24 {
 25 public:
 26         CharacterA()
 27         {
 28             m_chSymbol = 'A';
 29             m_nWeight = 100;
 30             m_nHeight = 200;
 31         }
 32         virtual ~CharacterA() {}
 33         void SetSize(int nWeight,int nHeight)
 34         {
 35             m_nWeight = nWeight;
 36             m_nHeight = nHeight;
 37         }
 38         void Display()
 39         {
 40             cout << "CharacterA:" << m_chSymbol << "(" << m_nWeight << "," << m_nHeight << ")" << endl;
 41         }
 42 };
 43 
 44 class CharacterB:public Character
 45 {
 46 public:
 47     CharacterB()
 48     {
 49         m_chSymbol = 'B';
 50         m_nWeight = 100;
 51         m_nHeight = 200;
 52     }
 53     virtual ~CharacterB() {}
 54     void SetSize(int nWeight,int nHeight)
 55     {
 56         m_nWeight = nWeight;
 57         m_nHeight = nHeight;
 58     }
 59     void Display()
 60     {
 61         cout << "CharacterB:" << m_chSymbol << "(" << m_nWeight << "," << m_nHeight << ")" << endl;
 62     }
 63 };
 64 
 65 class CharacterFactory
 66 {
 67 public:
 68     CharacterFactory()
 69     {
 70         m_mChar.insert(make_pair<char, Character*>('A', new CharacterA));
 71         m_mChar.insert(make_pair<char, Character*>('B', new CharacterB));
 72     }
 73     virtual ~CharacterFactory() {}
 74     Character* GetCharacter(char chIn)
 75     {
 76         map<char, Character*>::iterator it = m_mChar.find(chIn);
 77         if(it != m_mChar.end())
 78         {
 79             return (Character*)it->second;
 80         }
 81         return NULL;
 82     }
 83 private:
 84     std::map<char, Character*> m_mChar;
 85 
 86 };
 87 int _tmain(int argc, _TCHAR* argv[])
 88 {
 89 
 90     cout<<"享元模式:"<<endl;
 91     CharacterFactory *pFactory = new CharacterFactory();
 92     //内蕴状态 存储在享元对象内部并且不会随环境改变而改变
 93 
 94     Character* ch1 = pFactory->GetCharacter('A');
 95     ch1->Display();
 96     Character* ch2 = pFactory->GetCharacter('B');
 97     ch2->SetSize(500, 800);
 98     ch2->Display();
 99     system("pause");
100     return 0;
101 }

 

posted @ 2018-07-13 11:24  wxmwanggood  阅读(395)  评论(0编辑  收藏  举报