Prototype パターン

Advertisement

原型からオブジェクトを生成する

同じ内容のオブジェクトを複数作成したい場合、各オブジェクトを new で生成するより、原型を作成し、各オブジェクトを原型からコピーすることにより、オブジェクト生成のコストを低く抑えることができる。

サンプルコード

Figure クラス
public class Figure implements Cloneable{
    private String name = null;

    // デフォルトコンストラクタ
    public Figure(String name){
        this.name = name;
    }

    public String getName(){
        return this.name;
    }

    // clone の作成
    public Figure createClone(){
        Figure copy = null;
        try{
            copy = (Figure)this.clone();
        }catch(CloneNotSupportedException e){
            e.printStackTrace();
        }
        return copy;
    }
}

Main クラス
public class Main {
    public static void main(String[] args){
        Figure figure = new Figure("test");
        Figure copy = figure.createClone();

        System.out.println(figure.getName());
        System.out.println(copy.getName());
    }
}

Advertisement

ショートカット

634トップページ
このカテゴリのトップページに戻る
634ラボ

サイト検索

Google

Web サイト内

Y!ログール