C++设计模式——享元模式(flyweight pattern)

tech2022-08-06  135

一、原理讲解

1.1意图

运用共享技术有效地支持大量细粒度的对象。

1.2应用场景

一个程序中使用了大量的对象;完全由于使用大量的对象造成很大的存储开销;对象的大多数状态都可变为外部状态;如果删除对象的外部状态,那么可以用相对较少的共享对象取代很多组对象;应用程序不依赖于对象标识。

1.3结构图(UML图)

1.4代码实现步骤

a1 定义一个抽象接口类IFlyweight,定义一个接口函数operation()用于子类继承;(抽象类) a2 定义一个实现享元接口类ConcreteFlyweight,重写接口函数operation();(具体构建器) a3 定义一个工厂类Factory,主要功能是创建和获取享元对象,一次只能获取一个对象;

二、实现代码

Flyweight.cpp

#include <iostream> #include <map> #include <string> using namespace std; #define DELETE(pointer) delete pointer; pointer=nullptr class IFlyweight // 抽象接口 { public: IFlyweight() {} virtual ~IFlyweight() {} virtual void operation() = 0; }; class ConcreteFlyweight : public IFlyweight // 共享部分 { public: ConcreteFlyweight() {} ~ConcreteFlyweight() {} void operation() override { cout << "ConcreteFlyweight" << endl; } }; class UnsharedFlyweight : public IFlyweight // 共享部分 { public: UnsharedFlyweight() {} ~UnsharedFlyweight() {} void operation() override { cout << "UnsharedFlyweight" << endl; } }; class Factory //享元工厂,创建和返回享元对象 { public: IFlyweight* getFlyweight(string type) { if (!flyweights.count(type)) // 如果不存在,则创建一个共享模块;存在则不用创建直接返回对象 flyweights[type] = new ConcreteFlyweight(); return flyweights.at(type); } size_t size() { return flyweights.size(); } private: map<string, IFlyweight*> flyweights; }; void doFlyweightPattern() { Factory *factory = new Factory(); //创建享元工厂 IFlyweight *f1 = factory->getFlyweight(string("f1")); //获取f1的共享部分,非共享部分外部获取,不在factory获取 IFlyweight *f2 = factory->getFlyweight(string("f2")); IFlyweight *f3 = factory->getFlyweight(string("f3")); f1->operation(); f2->operation(); f3->operation(); cout << "factory->size()==" << factory->size() << endl; DELETE(f3); DELETE(f2); DELETE(f1); DELETE(factory); }

mian.cpp

#include <iostream> extern void doFlyweightPattern(); int main() { doFlyweightPattern(); system("pause"); return 1; }

三、总结

本文享元模式获取的是公共部分的对象,通过工厂统一管理,进行公共对象的创建和返回,方便管理大量对象创建和获取,节省了存储空间,但是消耗一定的时间。

四、参考内容

享元模式之C++实现 享元模式及C++实现 C++设计模式——享元模式 陈建忠设计模式(参考:哔哩哔哩C++设计模式!!!) Erich Gamma,Richard Helm.《设计模式 可复用面向对象软件的基础》[M].机械工业出版社,2019:

最新回复(0)