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

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(){
        //...
    }
};


猜你喜欢

转载自blog.csdn.net/wxf2012301351/article/details/74936500