码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2015-06-30 13:02:12      阅读:137      评论:0      收藏:0      [点我收藏+]

标签:

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

UML图:
技术分享

主要包括:

  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)

标签:

原文地址:http://blog.csdn.net/u012501459/article/details/46692469

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!