DEV Community

架构师小白
架构师小白

Posted on

享元模式深度指南:内存优化的核心艺术

享元模式深度指南

享元模式(Flyweight Pattern)是一种结构型设计模式,其核心思想是共享细粒度对象,以支持大量细粒度对象的高效运行。

核心概念

  • Flyweight(享元):享元接口
  • ConcreteFlyweight(具体享元):实现享元接口
  • FlyweightFactory(享元工厂):创建和管理享元对象

内部状态 vs 外部状态

  • 内部状态:存储在享元对象中,可被多个对象共享
  • 外部状态:存储在客户端,由客户端维护

实战案例

文本编辑器字符处理

interface Glyph {
    void draw(Window window);
}

class CharacterA implements Glyph {
    private char symbol = 'A';
    public void draw(Window w) { w.render(symbol); }
}

class GlyphFactory {
    private Map<Character,Glyph> pool = new HashMap<>();
    public Glyph get(char key) {
        return pool.computeIfAbsent(key, k->new CharacterA());
    }
}
Enter fullscreen mode Exit fullscreen mode

游戏子弹系统

class BulletType {
    private String shape, color;
    private int damage;
    public BulletType(String s, String c, int d) {
        shape=s; color=c; damage=d;
    }
}

class Bullet {
    private BulletType type;
    private double x, y;
    public Bullet(BulletType t, double x, double y) {
        this.type=t; this.x=x; this.y=y;
    }
}
Enter fullscreen mode Exit fullscreen mode

数据库连接池

class ConnectionPool {
    private List<Connection> available = new ArrayList<>();
    public ConnectionPool(String url, int size) throws SQLException {
        for(int i=0;i<size;i++) available.add(DriverManager.getConnection(url));
    }
}
Enter fullscreen mode Exit fullscreen mode

何时使用

  1. 大量相似对象(数十万级)
  2. 对象创建成本高
  3. 内存受限
  4. 状态可分离

注意事项

  • 线程安全:享元对象被多线程共享
  • 对象池管理:合理设置池大小
  • 权衡:少量对象时避免过度设计

总结

享元模式是优化内存的利器,适用于:

  • 游戏开发(粒子、子弹)
  • 图形编辑器
  • 缓存系统
  • 连接池

掌握享元模式,设计高性能高可扩展系统。


推荐阅读:《设计模式》- Erich Gamma

Top comments (0)