设计模式 —— 享元模式

 动机

  • 在软件系统中采用纯粹对象方案的问题在于大量细粒度的对象会很快充斥在系统中,从而带来很高的运行代价 — 主要指内存需求方面的代价。
  • 如何避免大量细粒度对象问题的同时,让外部客户程序仍然能够透明地使用面向对象的方式来进行操作?

模式定义

  运用共享技术有效地支持大量细粒度对象。       —— 《设计模式》GOF

 1 class Font {
 2 private:
 3 
 4     //unique object key
 5     string key;
 6     
 7     //object state
 8     //....
 9     
10 public:
11     Font(const string& key){
12         //...
13     }
14 };
15 ß
16 
17 class FontFactory{
18 private:
19     map<string,Font* > fontPool;
20     
21 public:
22     Font* GetFont(const string& key){
23 
24         map<string,Font*>::iterator item=fontPool.find(key);
25         
26         if(item!=footPool.end()){
27             return fontPool[key];
28         }
29         else{
30             Font* font = new Font(key);
31             fontPool[key]= font;
32             return font;
33         }
34 
35     }
36     
37     void clear(){
38         //...
39     }
40 };

原文地址:https://www.cnblogs.com/y4247464/p/15494918.html