Skip to content

享元模式

意图

运用共享技术有效支持大量细粒度对象。将状态分为内部状态(可共享)与外部状态(由调用方传入)。

类图

Java 示例

java
import java.util.*;

public class Glyph {
    private final char c; // 内部:可共享
    public Glyph(char c) { this.c = c; }
    public void draw(int x, int y) { // 外部:坐标
        System.out.println("draw '" + c + "' at " + x + "," + y);
    }
}

public class GlyphFactory {
    private final Map<Character, Glyph> pool = new HashMap<>();
    public Glyph get(char ch) {
        return pool.computeIfAbsent(ch, Glyph::new);
    }
}

Integer.valueOf(127) 缓存、String 常量池均有享元思想。

下一节:代理模式