概述

享元模式 (Flyweight Pattern) 又称轻量级模式。它使用共享技术有效支持大量细粒度对象的复用。

优点:大量减少内存中对象数量,相同/相似对象在内存中仅保留一份。
缺点:增加系统的复杂性。

class External {
  String external;
  
  External(String e) {
    external = e;
  }
  
  public String get() {
    return external;
  }
}

interface Flyweight {
  void op(External e);
}

class SubFlyweight1 implements Flyweight {
  String innerState;
  
  public SubFlyweight1(String inner) {
    innerState = inner;
  }
  
  public void op(External e) {
    // other
    e.get();
   // other
  }
}

class SubFlyweight2 implements Flyweight {
  String innerState;
  
  public SubFlyweight2(String inner) {
    innerState = inner;
  }
  
  public void op(External e) {
    // other
    e.get();
   // other
  }
}

class FlyweightFactory {
  ArrayList<Flyweight> fw = new ArrayList<>();
  
  public FlyweightFactory() {
    Flyweight sub1 = new SubFlyweight1("sub1");
    fw.add(sub1);
    Flyweight sub2 = new SubFlyweight2("sub2");
    fw.add(sub2);
  }
  
  public Flyweight getFlyweight(String type) {
    if (type == "SubFlyweight1") {
      return (SubFlyweight1)fw.get(0);
    } else if (type == "SubFlyweight2") {
      return (SubFlyweight2)fw.get(1);
    } else {
      return null;
    }
  }
}

图示:
image

参考

[1]. 刘伟, 设计模式. 2011.

 posted on 2023-06-30 23:12  x-yun  阅读(9)  评论(0编辑  收藏  举报