珠海网站建设 旭洁科技,亚马逊产品开发,广西网站制作公司,铁路建设监理网站本文章属于专栏- 概述 - 《设计模式#xff08;极简c版#xff09;》-CSDN博客 模式说明
方案#xff1a;享元模式是一种结构型设计模式#xff0c;旨在通过共享尽可能多的对象来最小化内存使用和提高性能。 优点 减少内存占用#xff1a;通过共享相似对象的状态#xf… 本文章属于专栏- 概述 - 《设计模式极简c版》-CSDN博客 模式说明
方案享元模式是一种结构型设计模式旨在通过共享尽可能多的对象来最小化内存使用和提高性能。 优点 减少内存占用通过共享相似对象的状态减少了对象的数量从而减少了内存消耗。提高性能由于减少了对象的数量降低了系统的负担提高了系统的性能。缺点 复杂性增加实现享元模式可能需要引入额外的复杂性例如维护共享对象的状态等。
本质思想将对象分为可共享的内部状态和不可变的外部状态通过共享内部状态来减少对象的数量以节省内存和提高性能。
实践建议在有大量相似对象时且相似部分状态不变时使用如果要变。则需要对象提供的接口全部线程安全则有性能风险需要慎重 代码示例
#include iostream
#include string
#include unordered_map// 抽象享元类
class Bird {
public:virtual void fly() const 0;
};// 具体享元类
class ConcreteBird : public Bird {
private:std::string type_;
public:ConcreteBird(const std::string type) : type_(type) {}void fly() const override {std::cout A type_ is flying! std::endl;}
};// 享元工厂类
class FlyweightFactory {
private:std::unordered_mapstd::string, const Bird* birds;
public:const Bird* getBird(const std::string type) {auto it birds.find(type);if (it birds.end()) {// 如果不存在该类型的鸟创建新的鸟对象birds[type] new ConcreteBird(type);return birds[type];}return it-second;}~FlyweightFactory() {for (auto pair : birds) {delete pair.second; // 释放内存}birds.clear();}
};int main() {FlyweightFactory factory;const Bird* bird1 factory.getBird(sparrow);const Bird* bird2 factory.getBird(sparrow);bird1-fly(); // 输出A sparrow is flying!bird2-fly(); // 输出A sparrow is flying!// 之后可以把bird1和bird2传递给其他对象实现共享return 0;
}