C++设计模式浅识享元模式

来源:互联网 发布:mac怎么删除abc输入法 编辑:程序博客网 时间:2024/06/01 20:26

享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。

四个角色类:

  1. Flyweight享元类:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。
  2. Flyweight享元工厂类:一个享元工厂,用来创建并管理Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个(如果不存在的话)。
  3. ConcreteFlyweight具体享元类:继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。
  4. UnSharedConcreteFlyweight不需共享的具体Flyweight子类、指那些不需要共享的Flyweight子类。因为Flyweight接口类共享成为可能,但并不强制共享。

模式实现:

//享元类class Flyweight{public:    virtual void Operation(int extrinsicState){}};//具体享元类class ConcreteFlyweight: public Flyweight{public:    virtual void Operation(int extrinsicState)override{        std::cout << "ConcreteFlyweight: " << extrinsicState << std::endl;    }};//不需共享的Flyweight子类class UnSharedConcreteFlyweight: public Flyweight{public:    virtual void Operation(int extrinsicState){        std::cout << "UnSharedConcreteFlyweight: " << extrinsicState << std::endl;    }};//享元工厂,用来创建并管理Flyweight对象class FlyweightFactory{private:    std::map<std::string, Flyweight*> flyweights;public:    FlyweightFactory(){        flyweights["X"] = new ConcreteFlyweight;        flyweights["Y"] = new ConcreteFlyweight;        flyweights["Z"] = new ConcreteFlyweight;    }    Flyweight* GetFlyweight(std::string key){        return (Flyweight*)flyweights[key];    }};

客户端:

//Clientint main(){    //外部状态    int extrinsicState = 22;    //工厂    FlyweightFactory *f = new FlyweightFactory;    Flyweight* fx = f->GetFlyweight("X");    fx->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 21    Flyweight* fy = f->GetFlyweight("Y");    fy->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 20    Flyweight* fz = f->GetFlyweight("Z");    fz->Operation(--extrinsicState);  //Output: ConcreteFlyweight: 19    Flyweight *uf = new UnSharedConcreteFlyweight;  //Output: UnSharedConcreteFlyweight: 18    uf->Operation(--extrinsicState);    return 0;}

享元模式好处:

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