享元模式

#include <iostream>
#include <string>
#include <map>
using namespace std;

class Flyweight
{
public:
    virtual void operation(int)=0;
};

class ConcreteFlyweight:public Flyweight
{
    void operation(int extrinsicState)
    {
        cout<<"具体FlyWeight: "<<extrinsicState<<endl;
    }
};

class UnsharedConcreteFlyweight:public Flyweight
{
    void operation(int extrinsicState)
    {
        cout<<"不共享的具体FlyWeight: "<<extrinsicState<<endl;        
    }
};

class FlyweightFactory
{
private:
    map<string,Flyweight*> flyweights;
public:
    FlyweightFactory()
    {
        flyweights["X"]=new ConcreteFlyweight();
        flyweights["Y"]=new ConcreteFlyweight();
        flyweights["Z"]=new ConcreteFlyweight();
    }
    Flyweight *getFlyweight(string key)
    {
        return (Flyweight *)flyweights[key];
    }
};


int main()
{
    int state=22;
    FlyweightFactory *f=new FlyweightFactory();

    Flyweight *fx=f->getFlyweight("X");
    fx->operation(--state);

    Flyweight *fy=f->getFlyweight("Y");
    fy->operation(--state);

    Flyweight *fz=f->getFlyweight("Z");
    fz->operation(--state);

    Flyweight *uf=new UnsharedConcreteFlyweight();
    uf->operation(--state);

    return 0;
}

GOOD:运用共享技术有效地支持大量细粒度的对象(对于 C++来说就是共用一 个内存块啦,对象指针指向同一个地方) 。
如果一个应用程序使用了大量的对象,而这些对象造成了很大的存储开销就应该 考虑使用。还有就是对象的大多数状态可以外部状态,如果删除对象的外部状态,那么可以 用较少的共享对象取代多组对象,此时可以考虑使用享元。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值