ڼС
梦回起点
做你害怕做的事,你会发现:不过如此
本站基于WordPress—主题by 设计窝
冀ICP备15003737号
梦回起点
Copyright © 2015-2024 All rights reserved.

享元模式——大话设计模式读书笔记

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

下面是享元模式的UML图:

Main

C++描述的代码:


/*
 * Copyright (c) 2018 initm.com All rights reserved.
 * 作者: Stupid
 * 描述: 享元模式
 * 完成时间: 2018-1-13 15:38
*/
#include <QCoreApplication>
#include <iostream>
#include <string>
#include <cstdlib>
#include <map>

class Flyweight{
public:
    virtual void opeatorion(int extrinsicstate) = 0;

};

class ConcreteFlyweight: public Flyweight{
public:
    void opeatorion(int extrinsicstate) final override{
        std::cout << "具体Flyweight:" << extrinsicstate << std::endl;
    }

};

class UnsharedConcreteFlyweight: public Flyweight{
public:
    void opeatorion(int extrinsicstate) final override{
        std::cout << "不共享的具体FlyWeight:" << extrinsicstate << std::endl;
    }

};

class FlyweightFactory{
private:
    std::map<std::string, Flyweight*> map;

public:
    FlyweightFactory(){
        //这里内存不足直接抛出std::bad_alloc算了
        map["X"] = new ConcreteFlyweight();
        map["Y"] = new ConcreteFlyweight();
        map["Z"] = new ConcreteFlyweight();
    }

    Flyweight* GetFlyweight(const std::string& key){
        return map[key];
    }
};

int main(int argc, char *argv[])
{
    system("chcp 65001");
    QCoreApplication a(argc, argv);

    int extrinsicstate = 22;
    FlyweightFactory* f = new FlyweightFactory;
    Flyweight* fx = f->GetFlyweight("X");
    fx->opeatorion(--extrinsicstate);

    Flyweight* fy = f->GetFlyweight("Y");
    fy->opeatorion(--extrinsicstate);

    Flyweight* fz = f->GetFlyweight("Z");
    fz->opeatorion(--extrinsicstate);

    Flyweight* uf = new UnsharedConcreteFlyweight;
    uf->opeatorion(--extrinsicstate);

    return a.exec();
}
2018-01-13