디자인패턴_Prototype Pattern of Creational Pattern

2021. 1. 26. 11:05카테고리 없음

Prototype는 "원형"이라는 의미로 원형이 되는 인스턴스로 새로운 인스턴스를 만드는 방식

따라서 객체에 의해 생성될 객체의 '타입'이 결정되는 생성 디자인 패턴

  • Prototype

인스턴스를 복사해 새로운 인스턴스를 만들기 위한 메소드 결정

 

  • ConcretePrototype

인스턴스를 복사해서 새로운 인스턴스를 만들기 위한 메소드 구현

 

  • Client

인스턴스 복사 메소드를 사용해 새로운 인스턴스 만듦

 

 

 

예제

Shape Class

public abstract class Shape implements Cloneable{
//clone() 메소드를 사용하기 위해 Cloneable 인터페이스를 구현

    protected Type type;
    abstract void draw()
    //추상 메소드로 정의

    @Override 
    public Object clone() throws CloneNotSupportedException{
        Object clone = null;

        try{
            clone = super.clone();
        } catch (RuntimeException e){
            e.printStackTrace();
        } catch (CloneNotSupportedException e) {
            e.printStackTrace();
        }
        return clone;
    }
}

Circle, Triangle, Rectangle Class

public class Circle extends Shape{
    public Circle(){
        this.type = Type.CIRCLE;
    }

    @Override
    void draw() {
        System.out.println("[Circle]입니다.");
    }
}

각각 Shape Class를 상속 받으며, draw() 메소드를 재정의

 

ShapeStore Class

public class ShapeStore{
    private static Map<Type, Shape> shapeMap = new HashMap<Type, Shape>();

    public void registerShape(){
        Rectangle rec = new Rectangle();  
        Circle cir = new Circle();
        Triangle tri = new Triangle();

        shapeMap.put(rec.type, rec);
        shapeMap.put(cir.type, cir);
        shapeMap.put(tri.type, tri);
    }
    public Shape getShape(Type type){
        return (Shape) shapeMap.get(type).clone();
    }
}

registerShape(): 메소드 호출시 복제에 사용할 객체를 인스턴스화해서 shapeMap에 저장

getShape(): 객체의 복사본을 반환

 

Main Class

public class Main{
    public static void main(String[] args){
        ShapeStor manager = new ShapeStore();
        manager.registerShape();

        Circle cir1 = (Circle)manager.getShape(Type.CIRCLE);
        cir1.draw();
        Circle cir2 = (Circle)manager.getShape(Type.CIRCLE);
        cir2.draw();

        Rectangle rec1 = (Rectangle)manager.getShape(Type.RECTANGLE);
        rec1.draw();

        Triangle tri1 = (Triangle)manager.getShape(Type.TRIANGLE);
        tri1.draw();
    }
}