本文章属于专栏- 概述 - 《设计模式(极简c++版)》-优快云博客
模式说明
- 方案:享元模式是一种结构型设计模式,旨在通过共享尽可能多的对象来最小化内存使用和提高性能。
- 优点
- 减少内存占用:通过共享相似对象的状态,减少了对象的数量,从而减少了内存消耗。
- 提高性能:由于减少了对象的数量,降低了系统的负担,提高了系统的性能。
- 缺点
- 复杂性增加:实现享元模式可能需要引入额外的复杂性,例如维护共享对象的状态等。
- 优点
本质思想:将对象分为可共享的内部状态和不可变的外部状态,通过共享内部状态来减少对象的数量,以节省内存和提高性能。
实践建议:在有大量相似对象时,且相似部分状态不变时使用(如果要变。则需要对象提供的接口全部线程安全,则有性能风险,需要慎重)
代码示例
#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_map<std::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;
}