프로토타입 패턴

프로토타입 패턴

프로토타입 패턴은 객체를 생성하는 방법 중 하나로, 객체를 복제하여 새로운 객체를 생성하는 방식입니다. 이 패턴은 기존 객체를 복제하여 새로운 객체를 생성하기 때문에 객체를 생성하는 데 드는 비용을 줄일 수 있습니다.

예제

프로토타입 패턴의 예제는 아래와 같습니다. 이 예제는 미리 만들어진 도형(Shape) 객체를 복제하여 새로운 도형을 만드는 예제입니다.
public abstract class Shape implements Cloneable { // ... public Object clone() { Object clone = null; try { clone = super.clone(); } catch (CloneNotSupportedException e) { e.printStackTrace(); } return clone; } } public class Rectangle extends Shape { // ... } public class Square extends Shape { // ... } 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(); } public static void loadCache() { // ... } } 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()); } }
Plain Text
복사
위 예제에서는 ShapeCache 클래스를 사용하여 이미 만들어진 도형 객체를 캐싱하고, 이를 복제하여 새로운 도형 객체를 만듭니다.

언제 사용하는가?

프로토타입 패턴은 객체를 생성하는 과정에서 많은 비용이 들거나 복잡한 과정을 거쳐야 하는 경우 사용할 수 있습니다. 또한 객체 생성 과정에서 발생할 수 있는 오류를 최소화하고자 하는 경우에도 사용할 수 있습니다.

참고 링크