← 返回博客列表

模式特点

运用共享技术有效地支持大量细粒度的对象。享元模式通过共享对象来减少内存使用,将对象状态分为内部状态(共享)和外部状态(不共享)。

类图

类图

应用场景

示例代码(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);
}