1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

デザインパターン学習メモ:「Prototype」

Posted at

このパターンの目的

GoF本より引用する。

生成すべきオブジェクトの種類を原型となるインスタンスを使って明確にし、それをコピーすることで新たなオブジェクトの生成を行う。(P.127)

実装例

ShapeFactory.java
// Client
public class ShapeFactory {
	private Circle prototypeCircle;
	private Rectangle prototypeRectangle;

	public ShapeFactory(Circle circle, Rectangle rectangle) {
		this.prototypeCircle = circle;
		this.prototypeRectangle = rectangle;
	}

	public Circle makeCircle(double radius) {
		Circle circle = prototypeCircle.createClone();
		return circle.initialize(radius);
	}

	public Rectangle makeRectangle(double side1, double side2) {
		Rectangle rectangle = prototypeRectangle.createClone();
		return rectangle.initialize(side1, side2);
	}
}
Circle.java
// Prototype
public class Circle {
	private double radius;

	public Circle(double radius) {
		this.radius = radius;
	}

	public Circle initialize(double radius) {
		this.radius = radius;
		return this;
	}

	public Circle createClone() {
		try {
			return (Circle) clone();
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException("Clone Failed");
		}
	}
}
Rectangle.java
// Prototype
public class Rectangle {
	private double side1;
	private double side2;

	public Rectangle(double side1, double side2) {
		this.side1 = side1;
		this.side2 = side2;
	}

	public Rectangle initialize(double side1, double side2) {
		this.side1 = side1;
		this.side2 = side2;
		return this;
	}

	public Rectangle createClone() {
		try {
			return (Rectangle) clone();
		} catch (CloneNotSupportedException e) {
			throw new RuntimeException("Clone Failed");
		}
	}
}

利点

  • 他の生成パターンと同様に、Clientは具体的なクラス名を知らずにオブジェクトを取得できる
  • 生成するオブジェクトの追加・削除を実行時に行える
    • 上記の実装例では可能になっていないが、PrototypeをListなどで保持し、実行時に登録や削除を行うようにできる
  • システム全体で必要になるクラス数を減らすことができる
    • クラスのフィールド値によって異なるクラスにした場合と同じことが表現できる場合には、それぞれPrototypeとしてClientに登録することで、あえてクラス化する必要がなくなる

参考文献

  • エリック ガンマ、ラルフ ジョンソン、リチャード ヘルム、ジョン プリシディース(1999)『オブジェクト指向における再利用のためのデザインパターン 改訂版』本位田 真一、吉田 和樹 監訳、SBクリエイティブ
1
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?