享元模式C++

2018-05-11  本文已影响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;
}

应用场景

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

上一篇下一篇

猜你喜欢

热点阅读