设计模式之二十二:享元方式(FlyWeight)

设计模式之二十二:享元模式(FlyWeight)

享元模式:
使用共享技术有效地支持大量细粒度的对象。
Use sharing to support large numbers of fine-grained objects efficiently.
这个设计模式和它的名字一样核心是为了共享代码。

UML图:
设计模式之二十二:享元方式(FlyWeight)

主要包括:

  1. FlyWeight:声明了一个接口,通过这个接口所有的FlyWeight能够接受并作用于外部的状态。
  2. ConcreteFlyWeight:实现了FlyWeight声明的接口,并且可能会增加一些内部状态。
  3. UnSharedConcreteFlyWeight:指那些不需要共享的FlyWeight。
  4. FlyWeightFactory:创建和管理FlyWeight对象,确保FlyWeight对象被恰当的共享。

C++代码:

#include <iostream>
#include <map>

using namespace std;


class FlyWeight
{
        public:
                virtual void operation(int extrinsicState)=0;

};

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
{
        public:
                FlyWeightFactory()
                {
                    flyWeights["X"]=new ConcreteFlyWeight();
                    flyWeights["Y"]=new ConcreteFlyWeight();
                    flyWeights["Z"]=new ConcreteFlyWeight();
                }

                FlyWeight * getFlyWeight(string key)
                {
                    return flyWeights[key];
                }
        private:
                map<string,FlyWeight *> flyWeights;

};


int main()
{
    cout<<"基本享元模式代码"<<endl;
    int extrinsicState=22;
    FlyWeightFactory *factory=new FlyWeightFactory();

    FlyWeight * fx=factory->getFlyWeight("X");
    fx->operation(--extrinsicState);

    FlyWeight * fy=factory->getFlyWeight("Y");
    fy->operation(--extrinsicState);

    FlyWeight * fz=factory->getFlyWeight("Z");
    fz->operation(--extrinsicState);

    FlyWeight * fu=new UnSharedConcreteFlyWeight();
    fu->operation(--extrinsicState);

    delete factory;
    delete fx;
    delete fy;
    delete fz;
    delete fu;

    return 0;
}

执行输出:
设计模式之二十二:享元方式(FlyWeight)

版权声明:本文为博主原创文章,未经博主允许不得转载。