模式特点
运用共享技术有效地支持大量细粒度的对象。享元模式通过共享对象来减少内存使用,将对象状态分为内部状态(共享)和外部状态(不共享)。
- 内部状态:不变的部分,可被多个对象共享
- 外部状态:变化的部分,由客户端传入
- 通过享元工厂管理共享对象的创建和缓存
- 大幅减少相似对象的内存占用
类图
应用场景
- Qt 中 QString 的隐式共享(Copy-On-Write)机制
- 游戏中的粒子系统:大量粒子共享纹理和模型
- 文本编辑器中的字符渲染:共享字形数据
- 地图瓦片:相同图块共享渲染数据
- 线程池:复用线程对象避免频繁创建销毁
示例代码(C++)
// 享元对象 - 共享的纹理 class Texture { std::string m_type; // 内部状态(共享) public: Texture(const std::string& type) : m_type(type) { std::cout << "加载纹理: " << type << std::endl; } void render(int x, int y) { // x,y 为外部状态 std::cout << "渲染 " << m_type << " 在(" << x << "," << y << ")" << std::endl; } }; // 享元工厂 class TextureFactory { std::map<std::string, Texture*> m_pool; public: Texture* getTexture(const std::string& type) { if (m_pool.find(type) == m_pool.end()) m_pool[type] = new Texture(type); return m_pool[type]; // 复用已有对象 } }; // 使用:1000个粒子只创建3种纹理 TextureFactory factory; for (int i = 0; i < 1000; i++) { Texture* tex = factory.getTexture(i % 3 == 0 ? "fire" : i % 3 == 1 ? "smoke" : "spark"); tex->render(i % 100, i / 100); }