📢 この記事は gemini-3-flash-preview によって翻訳されました
プロトタイプパターン (Prototype Pattern) - オブジェクト生成に関するパターン
意図
原型のインスタンスを使って生成するオブジェクトの種類を特定して、その原型をコピーすることで新しいオブジェクトを作るんだ。
構造

役割:
- Prototype:自分自身をコピーするためのインターフェースを宣言するよ。
- ConcretePrototype:自分自身をコピーする処理を実装するんだ。
- Client:原型に自分自身をコピーさせて、新しいオブジェクトを作るよ。
使いどころ
Prototype パターンは以下のような場合に適しているよ:
- システムが製品の生成・構成・表現方法に依存しないようにしたいとき。
- インスタンス化するクラスが実行時に指定されるとき(例えば、動的読み込みなど)。
- 製品のクラス階層と並行した工場クラスの階層を作るのを避けたいとき。
- クラスのインスタンスが、いくつかの異なる状態の組み合わせのうちの一つにしかならないとき。あらかじめいくつかの原型を用意してクローンするほうが、毎回手動で適切な状態のインスタンスを作るよりも便利な場合があるんだ。
例 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| public class main{
Product p1 = new Product(2023, 3.03);
System.out.println(p1.getId() + " " + p1.getPrice());
// Product p2 = new Product(2023, 3.03);
Product p2 = (Product) p1.Clone();
System.out.println(p2.getId() + " " + p2.getPrice());
}
interface Prototype{
public Object Clone();
}
class Product implements Prototype{
private int id;
private double price;
public Product(){}
public Product(int id, double price){
this.id = id;
this.price = price;
}
public int getId(){
return this.id;
}
public double getPrice(){
return this.price;
}
public void setId(int id){
this.id = id;
}
public void setPrice(double price){
this.price = price;
}
@Override
public Object Clone(){
Product object = new Product();
object.id = this.id;
object.price = this.price;
return object;
}
}
|
例 2 (公式インターフェースを使う場合)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
| public class main{
Product p1 = new Product(2023, 3.03);
System.out.println(p1.getId() + " " + p1.getPrice());
// Product p2 = new Product(2023, 3.03);
Product p2 = (Product) p1.clone();
System.out.println(p2.getId() + " " + p2.getPrice());
}
// 削除
// interface Prototype{
// public Object Clone();
// }
// インターフェースを実装
class Product implements Cloneable{
private int id;
private double price;
public Product(){}
public Product(int id, double price){
this.id = id;
this.price = price;
}
public int getId(){
return this.id;
}
public double getPrice(){
return this.price;
}
public void setId(int id){
this.id = id;
}
public void setPrice(double price){
this.price = price;
}
// メソッドをオーバーライド
@Override
public Object clone(){
return super.clone();
}
}
|