欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

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

程序员文章站 2023-12-27 13:56:21
...
享元模式(Flyweight):运用共享技术有效地支持大量细粒度的对象。

四个角色类:

Flyweight享元类:所有具体享元类的超类或接口,通过这个接口,Flyweight可以接受并作用于外部状态。

Flyweight享元工厂类:一个享元工厂,用来创建并管理Flyweight,当用户请求一个Flyweight时,FlyweightFactory对象提供一个已创建的实例或者创建一个(如果不存在的话)。

ConcreteFlyweight具体享元类:继承Flyweight超类或实现Flyweight接口,并为内部状态增加存储空间。

UnSharedConcreteFlyweight不需共享的具体Flyweight子类、指那些不需要共享的Flyweight子类。因为Flyweight接口类共享成为可能,但并不强制共享。

模式实现:
[code]//享元类
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];
    }
};

客户端:

[code]//Client
int 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;
}

享元模式好处:

如果一个应用程序使用了大量的对象,而大量的这些对象造成了很大的存储开销时就应该考虑使用。

对象的大多数状态可以使用外部状态,如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象,此时可以考虑使用享元模式。

以上就是C++设计模式浅识享元模式的内容,更多相关内容请关注PHP中文网(www.php.cn)!


上一篇:

下一篇: