设计模式(十五)flyweight享元模式

来源:互联网 发布:国家漏洞数据库 编辑:程序博客网 时间:2024/06/05 15:47

1.使用场景:大量细粒度的对象充斥在系统中
2.定义:运用共享技术有效的支持大量细粒度的对象
3.目标:降低对象个数
4.注意:要根据实际情况确定成本的大小,该设计模式仍有额外的成本


flyweight享元模式代码:

class Font {private:    //unique object key    string key;        //object state    //....    public:    Font(const string& key){        //...    }};ßclass FontFactory{private:    map<string,Font* > fontPool;    public:    Font* GetFont(const string& key){        map<string,Font*>::iterator item=fontPool.find(key);                if(item!=footPool.end()){            return fontPool[key];        }        else{            Font* font = new Font(key);            fontPool[key]= font;            return font;        }    }        void clear(){        //...    }};