LoginSignup
0
0

More than 3 years have passed since last update.

Prototype Pattern

Last updated at Posted at 2020-11-09

Prototype Pattern

インスタンスをコピーして使う

このページでは
・Prototype Patternの確認
・Mapコレクションにインスタンスを格納して使う
について記載します

Design Pattarm MENU

Prototype Patternの確認

以下のクラス構成で確認します

クラス 説明
samPrototype.class 自分の複製を作るメソッドを持つ
user(Main.class) 動作を確認

*user 他の開発者がこのパターンを利用する、という意味合いを含みます

clone()メソッドを使う場合には、java.lang.Cloneableインターフェイスを実装します

それでは確認します

samPrototype.class
class samPrototype implements Cloneable{         // java.lang.Cloneableを実装する
  void todo(){System.out.println("prototype");}

  samPrototype getClone(){
    samPrototype pro = null;
    try{pro=(samPrototype) clone();              // clone()を実行し、自身のコピーを作る
    }catch(Exception e){}
    return pro;
  }
}
user(Main.class)
public static void main(String[] args){
  samPrototype pr = new samPrototype();
  pr.getClone().todo();
}}

Mapコレクションにインスタンスを格納して使う

Prototype Patternは、事前に複数のインスタンスを登録しておき
必要に応じてclone()を実行する利用法があります

以下の構成で実装します

クラス名 説明
prototype.interface Cloneableを実装し、clone()メソッドを定義する
prototypeImple.class prototype.interfaceを実装してclone()メソッドを実装します
prototypeManager.class prototypeを実装したクラスインスタンスをコレクションに保持
prototype型にあるclone()メソッドを利用してインスタンスを発行する
user(Main.class) 動作を確認します

ではクラスを作ります

prototype.interface
interface prototype extends Cloneable{
  void todo();
  prototype exeClone();
}
prototypeImple.class
class prototypeImple implements prototype{
  String name;
  prototypeImple(String name){this.name=name;}

  public void todo(){System.out.println(name);}

  public prototype exeClone(){
      prototype pro = null;
      try{pro = (prototype) clone();}catch(Exception e){}
      return pro;
  }
}
usr(Main.class)
public static void main(String[] args){
  prototypeManager pm = new prototypeManager();
  pm.set(0, new prototypeImple("A"));
  pm.set(1, new prototypeImple("B"));
  prototype p1 = pm.getClone(0);
  prototype p2 = pm.getClone(1);
  p1.todo();
  p2.todo();
}}
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