首页 > 其他 > 详细

Charpter26 享元模式

时间:2020-04-05 00:58:24      阅读:72      评论:0      收藏:0      [点我收藏+]

享元模式简介

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

个人认为,其实享元模式,就是共享相同的对象,通过相同的对象和不同对象之间的组合达到满足多样需求的目的。

享元模式可以避免大量的非常相似类的开销。在程序设计中,有时需要生成大量细颗粒度的类的实例来表示数据。如果能发现这些实例除了几个参数外基本上都是相同的,有时就能够大幅度地减少需要实例化的类的数量。如果能把那些参数移到类的实例的外面,在方法调用时,将他们传递进来,就可以通过共享大幅度地减少单个实例的数目。

比如下棋,一盘棋有361个空位可以放棋子,难道我们就应该创建361个棋子对象才能下一盘棋吗,其实这里面棋子外形都是一样的,所以只需要实例化一个棋子(此为共享的对象),然后用另一个类来表示颜色和位置。这样就有效的减少了实例化棋子的数量,减少了存储空间上的开销。

享元模式UML类图

技术分享图片

C++代码实现

// Flyweight接口类
#ifndef _FLYWEIGHT_HPP
#define _FLYWEIGHT_HPP
class Flyweight{
public:
    virtual void myOperation(int) = 0;
};

#endif
// ConcreteFlyweight类
#ifndef _CONCRETEFLYWEIGHT_HPP
#define _CONCRETEFLYWEIGHT_HPP
#include"flyweight.hpp"
#include<iostream>
using namespace std;

class ConcreteFlyweight:public Flyweight{
public:
    virtual void myOperation(int extrinsicState)override{
        cout << "ConcreteFlyweight: " << extrinsicState << endl;
    }
};

#endif
// FlyweightFactory类
#include<map>
#include<string>
#include"concreteflyweight.hpp"

using namespace std;

class FlyweightFactory{
public:
    Flyweight* getFlyweight(string str){
        map<string,Flyweight*>::iterator it;
        it = flyweightMap.find(str);
        if(it != flyweightMap.end()){
            return it->second;    
        }
        else {
            auto tmp = new ConcreteFlyweight();
            flyweightMap.emplace(str,tmp);
            return tmp;
        }
    }
    int getCnt(){
        return flyweightMap.size();
    }
private:
    map<string, Flyweight*> flyweightMap;
};

#endif
// UnsharedConcreteFlyweight类
#ifndef _UNSHAREDCONCRETEFLYWEIGHT_HPP
#define _UNSHAREDCONCRETEFLYWEIGHT_HPP

#include<iostream>
#include"flyweight.hpp"

using namespace std;

class UnsharedConcreteFlyweight : public Flyweight{
public:
    virtual void myOperation(int extrinsicState)override{
    cout << "UnsharedConcreteFlyweight: " << extrinsicState << endl;
    }
};
#endif
// 客户端代码
#include<iostream>
#include"concreteflyweight.hpp"
#include"unsharedconcreteflyweight.hpp"
#include"flyweightfactory.hpp"

using namespace std;

int main(){
    int extrinsicState = 10;
    FlyweightFactory* fwFactory = new FlyweightFactory();
    Flyweight* fw1 =  fwFactory->getFlyweight("#1");        
    Flyweight* fw2 = fwFactory->getFlyweight("#2"); 
    Flyweight* fw3 = fwFactory->getFlyweight("#3");
    fw1 = fwFactory->getFlyweight("#1");
    fw1->myOperation(extrinsicState--);
    fw2->myOperation(extrinsicState--);
    fw3->myOperation(extrinsicState--);

    UnsharedConcreteFlyweight* ufw = new UnsharedConcreteFlyweight();     
    ufw->myOperation(extrinsicState--);

    cout << "The objects number: " << fwFactory->getCnt() << endl;

    getchar();
    return 0;
}

 运行结果

技术分享图片

 

Charpter26 享元模式

原文:https://www.cnblogs.com/yb-blogs/p/12635059.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!