美文网首页
享元模式C++

享元模式C++

作者: 涵仔睡觉 | 来源:发表于2018-05-11 11:00 被阅读0次

    享元模式,就是运用共享技术有效地支持大量细粒度的对象。

    享元模式结构图

    image

    享元模式基本代码

    #include <iostream>
    #include <map>
    #include <string>
    using namespace std;
    
    class Flyweight {
    public:
        virtual void Operation(int extrinsicstate) = 0;
        virtual ~Flyweight() {}
    };
    
    class ConcreteFlyweight : public Flyweight {
    public:
        void Operation(int extrinsicstate) {
            cout << "ConcreteFlyweight: " << extrinsicstate << endl;
        }
    };
    
    class UnsharedConcreteFlyweight : public Flyweight { // 不强制共享对象,但也可以共享
    public:
        void Operation(int extrinsicstate) {
            cout << "UnsharedConcreteFlyweight: " << extrinsicstate << endl;
        }
    };
    
    class FlyweightFactory {
    private:
        map<string, Flyweight*> flyweights;
    public:
        Flyweight* GetFlyweight(string key) {
            if (flyweights[key] == NULL) flyweights[key] = new ConcreteFlyweight();
            return (Flyweight*)flyweights[key];
        }
    };
    
    int main() {
        int extrinsicstate = 22;   // 外部状态
    
        FlyweightFactory* f = new FlyweightFactory();
        Flyweight* fx = f->GetFlyweight("X");    // X、Y、Z为内部状态
        fx->Operation(--extrinsicstate);    // ConcreteFlyweight: 21
    
        Flyweight* fy = f->GetFlyweight("Y");
        fy->Operation(--extrinsicstate);    // ConcreteFlyweight: 20
    
        Flyweight* fz = f->GetFlyweight("Z"); // ConcreteFlyweight: 19
        fz->Operation(--extrinsicstate);    
    
        UnsharedConcreteFlyweight* uf = new UnsharedConcreteFlyweight();
        uf->Operation(--extrinsicstate);    // UnsharedConcreteFlyweight: 18
    
        delete fx;
        delete fy;
        delete fz;
        delete f;
        delete uf;
    
        return 0;
    }
    

    应用场景

    享元模式可以避免大量非常相似的开销。在程序设计中,有时需要生成大量细粒度的类实例来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的,有时就能够大幅度地减少需要实例化的类的数量。如果能把那些参数移到类实例的外面,在方法调用时将它们传递进来,就可以通过共享大幅度地减少单个实例的数目。

    • 如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销时就应该考虑使用享元模式;
    • 对象的大多数状态可以是外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑用享元模式。

    相关文章

      网友评论

          本文标题:享元模式C++

          本文链接:https://www.haomeiwen.com/subject/quffdftx.html