享元模式通过共享内部状态减少内存开销,分离可变外部状态与不可变内部状态。示例中TreeType存储种类、颜色、纹理等内部状态,由TreeFactory管理复用;位置作为外部状态在draw时传入。Forest中种植多棵树,相同类型的树共享同一TreeType实例,避免重复创建,显著降低内存使用,适用于对象数量庞大且存在重复数据的场景。

享元模式(Flyweight Pattern)是一种结构型设计模式,主要用于减少创建大量相似对象时的内存开销。它的核心思想是:通过共享尽可能多的数据来支持大量细粒度的对象。在C++中,实现享元模式的关键在于分离**内部状态(Intrinsic State)** 和 **外部状态(Extrinsic State)**。
内部状态是可共享的、不会随环境改变的状态;外部状态是依赖上下文、不可共享的部分,通常由客户端传入。
享元模式的基本结构
一个典型的享元模式包含以下几个部分:
- Flyweight(抽象享元类):定义接口,接受外部状态作为参数。
- ConcreteFlyweight(具体享元类):实现 Flyweight 接口,并存储内部状态。
- UnsharedConcreteFlyweight(非共享具体享元):不需要共享的对象,可选。
- FlyweightFactory(享元工厂):负责管理享元对象,确保共享对象能被正确复用。
C++ 实现示例
假设我们要绘制森林中的树,每棵树有类型(种类、颜色、纹理)和位置(X, Y)。其中“种类、颜色、纹理”是内部状态,可以共享;“位置”是外部状态,每次调用时传入。
立即学习“C++免费学习笔记(深入)”;
// TreeType.h - 共享的内部状态 class TreeType { private: std::string name; std::string color; std::string texture;
public: TreeType(const std::string& n, const std::string& c, const std::string& t) : name(n), color(c), texture(t) {}
void draw(int x, int y) const {
std::cout << "Drawing " << name << " tree at (" << x << "," << y
<< ") with color " << color << " and texture " << texture << "\n";
}};
// TreeFactory.h - 享元工厂 class TreeFactory { private: std::vector<:unique_ptr>> treeTypes;
public:
TreeType* getTreeType(const std::string& name, const std::string& color, const std::string& texture) {
for (const auto& tt : treeTypes) {
if (tt->getName() == name && tt->getColor() == color && tt->getTexture() == texture) {
return tt.get();
}
}
// 没找到就创建新的
treeTypes.push_back(std::make_unique
上面代码中我们省略了 TreeType 的 getter 方法,实际使用中需要添加 getName(), getColor(), getTexture() 等函数用于比较。
// Tree.h - 外部接口,使用享元 class Tree { private: int x, y; // 外部状态 TreeType* type; // 内部状态(共享)
public: Tree(int x, int y, TreeType* type) : x(x), y(y), type(type) {}
void draw() const {
type->draw(x, y);
}};
// Forest.h - 容器类 class Forest { private: std::vector<:unique_ptr>> trees; TreeFactory factory;
public:
void plantTree(int x, int y, const std::string& name, const std::string& color, const std::string& texture) {
TreeType* type = factory.getTreeType(name, color, texture);
trees.push_back(std::make_unique
void draw() const {
for (const auto& tree : trees) {
tree->draw();
}
}};
使用示例
int main() { Forest forest;forest.plantTree(1, 2, "Pine", "Green", "Needle"); forest.plantTree(3, 4, "Pine", "Green", "Needle"); // 复用同一类型 forest.plantTree(5, 6, "Oak", "Brown", "Broad"); forest.draw(); return 0;
}
输出结果:
Drawing Pine tree at (1,2) with color Green and texture Needle Drawing Pine tree at (3,4) with color Green and texture Needle Drawing Oak tree at (5,6) with color Brown and texture Broad
虽然创建了三棵树,但只生成了两个 TreeType 对象,“Pine” 类型被成功复用。
关键点总结
实现享元模式需要注意以下几点:
- 把不变的状态提取出来作为享元对象,通常是构造参数固定的资源。
- 享元对象必须是不可变的或线程安全的,否则共享会出问题。
- 工厂类应保证相同参数只创建一次享元对象,可用哈希表优化查找。
- 外部状态不能保存在享元中,必须在方法调用时传入。
基本上就这些。享元模式适合对象数量巨大且存在大量重复数据的场景,比如文字编辑器中的字符格式、游戏中的粒子系统或地图元素。合理使用能显著降低内存占用。









