Design-pattern-prototype-pattern
デザインパターン-プロトタイプパターン
プロトタイプパターンとは、パフォーマンスを考慮しながら複製オブジェクトを作成することです。 このタイプのデザインパターンは、オブジェクトを作成する最適な方法の1つであるため、作成パターンの下にあります。
このパターンには、現在のオブジェクトのクローンを作成するように指示するプロトタイプインターフェイスの実装が含まれます。 このパターンは、オブジェクトの直接作成にコストがかかる場合に使用されます。 たとえば、高価なデータベース操作の後にオブジェクトが作成されます。 オブジェクトをキャッシュし、次のリクエストでそのクローンを返し、必要に応じてデータベースを更新して、データベース呼び出しを減らします。
実装
抽象クラス_Shape_と、_Shape_クラスを拡張する具象クラスを作成します。 クラス_ShapeCache_は、シェープオブジェクトを_Hashtable_に保存し、要求時にクローンを返す次のステップとして定義されます。
PrototypPatternDemo、デモクラスは_ShapeCache_クラスを使用して_Shape_オブジェクトを取得します。
ステップ1
_Clonable_インターフェイスを実装する抽象クラスを作成します。
Shape.java
public abstract class Shape implements Cloneable {
private String id;
protected String type;
abstract void draw();
public String getType(){
return type;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Object clone() {
Object clone = null;
try {
clone = super.clone();
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
return clone;
}
}
ステップ2
上記のクラスを拡張する具象クラスを作成します。
Rectangle.java
public class Rectangle extends Shape {
public Rectangle(){
type = "Rectangle";
}
@Override
public void draw() {
System.out.println("Inside Rectangle::draw() method.");
}
}
Square.java
public class Square extends Shape {
public Square(){
type = "Square";
}
@Override
public void draw() {
System.out.println("Inside Square::draw() method.");
}
}
Circle.java
public class Circle extends Shape {
public Circle(){
type = "Circle";
}
@Override
public void draw() {
System.out.println("Inside Circle::draw() method.");
}
}
ステップ3
データベースから具体的なクラスを取得するクラスを作成し、_Hashtable_に保存します。
ShapeCache.java
import java.util.Hashtable;
public class ShapeCache {
private static Hashtable<String, Shape> shapeMap = new Hashtable<String, Shape>();
public static Shape getShape(String shapeId) {
Shape cachedShape = shapeMap.get(shapeId);
return (Shape) cachedShape.clone();
}
//for each shape run database query and create shape
//shapeMap.put(shapeKey, shape);
//for example, we are adding three shapes
public static void loadCache() {
Circle circle = new Circle();
circle.setId("1");
shapeMap.put(circle.getId(),circle);
Square square = new Square();
square.setId("2");
shapeMap.put(square.getId(),square);
Rectangle rectangle = new Rectangle();
rectangle.setId("3");
shapeMap.put(rectangle.getId(), rectangle);
}
}
ステップ4
_PrototypePatternDemo_は、_ShapeCache_クラスを使用して、_Hashtable_に格納されている形状のクローンを取得します。
PrototypePatternDemo.java
public class PrototypePatternDemo {
public static void main(String[] args) {
ShapeCache.loadCache();
Shape clonedShape = (Shape) ShapeCache.getShape("1");
System.out.println("Shape : " + clonedShape.getType());
Shape clonedShape2 = (Shape) ShapeCache.getShape("2");
System.out.println("Shape : " + clonedShape2.getType());
Shape clonedShape3 = (Shape) ShapeCache.getShape("3");
System.out.println("Shape : " + clonedShape3.getType());
}
}
ステップ5
出力を確認します。
Shape : Circle
Shape : Square
Shape : Rectangle