LoginSignup
0
0

More than 3 years have passed since last update.

Flyweight Pattern

Last updated at Posted at 2020-11-06

Flyweight Pattern

インスタンスを多重生成せずに使いまわしてメモリに優しくなる

このページでは下記について記載します
・Flyweightの基本構成
・実装

Design Pattarm MENU

Flyweightの基本構成

クラス 説明
factory.class sam.classのインスタンスを重複生成させない
sam.class userがインスタンスを生成する対象クラス
user(Main.class) factory.classを経由してsam.classインスタンスを生成する

*user 他の開発者がこのパターンを利用する、という意味合いを含みます
*user 他の開発者がこのパターンを利用する、という意味合いを含みます
factory.classとsam.classの基本構造

factory.class
class factory{
  Map map;
  sam getSam(){}
}

factoryでは、生成したsam()インスタンスをMapで保持し
重複しないよう管理します

sam.class
class sam{
  String s;
  sam(){}
}

sam()はコンストラクタでString sを登録します

下記で基本的な構造を実装します

factory.class
class factory{
  Map map = new HashMap();        // sam()インスタンスを格納します
  sam getSam(String key){         
      sam s = (sam) map.get(key); // mapからインスタンスを取得します
      if(s != null){return s;}    // mapにインスタンスがあればuserに渡します
      sam sm= new sam(key);       // mapにインスタンスがなければインスタンスを生成
      map.put(key,sm);            // インスタンスを新規生成したらmapに登録します
      return sm;                  // userにインスタンスを発行します
  }
}
sam.class
class sam{
  String s;
  sam(String s){}
}

実装

前述のコードには問題があります。
factoryにはMapを持たせsam()インスタンスを管理させますが
factory自身が複数インタンス化されると、その数だけ異なるMapが誕生します

そうなると適切にsam()インスタンスを管理できません
そこでfactory.classをシングルトンとします
(それだけではMapの複製を防げないのですがとりあえずの処理として)

さらに検証できるようMap内容を表示するprint()メソッドも実装します

factory.class
class factory{
  Map map = new HashMap();
  private static final factory fac = new factory();

  private factory(){}
  static  factory getInstance(){
          return fac;
  }

  sam getSam(String key){
      sam s = (sam) map.get(key);
      if( s != null){return s;}
      sam sm = new sam(key);
      map.put(key,sm);
      return sm;
  }

  void print(){
    Iterator it = map.keySet().iterator();
    while(it.hasNext()){
      sam s = (sam) map.get(it.next());
      System.out.println(s+":"+s.get());
    }
  }
}
sam.class
class sam{
  private String s;
  sam(String s){this.s=s;}
  String get(){return this.s;}
}
user(Main.class)
public static void main(String[] args){
  factory f = factory.getInstance();
  f.getSam("a");
  f.getSam("b");
  f.getSam("c");
  f.getSam("a");
  f.print();
}}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0