IT_Fundamental/디자인 패턴
Prototype Pattern(프로토 타입 패턴) - 1
surhommejk
2017. 12. 7. 16:24
Prototype Pattern(프로토 타입 패턴)
프로그램 코드를 작성하다보면 기존에 만들어진 인스턴스의 내용을 일부 수정하여 사용하고 싶을 때가 있다. 그런 경우 객체를 새로 생성할 때는 사용하는 new Object() 메서드보다 [그림 5-31]처럼 clone() 메서드를 이용해 기존의 것을 복사하여 일부만 바꿔 인스턴스를 생성할 수 있다. 이런 개념을 확장하여 처음부터 일반적인 prototype(원형)을 만들어놓고, 그것을 복사한 후 필요한 부분만 수정하면 new Object() 메서드로 객체를 생성하는 것보다 편리하다.
[네이버 지식백과] prototype 패턴 (쉽게 배우는 소프트웨어 공학, 2015. 11. 30., 한빛아카데미(주))
package Prototype;
public class Shape implements Cloneable {
private String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
}
package Prototype;
public class Circle extends Shape {
int x, y, r;
public Circle() {
}
public Circle(int x, int y, int r) {
this.x = x;
this.y = y;
this.r = r;
}
public int getX() {
return x;
}
public void setX(int x) {
this.x = x;
}
public int getY() {
return y;
}
public void setY(int y) {
this.y = y;
}
public int getR() {
return r;
}
public void setR(int r) {
this.r = r;
}
public Circle copy() throws CloneNotSupportedException {
Circle circle = (Circle) clone(); // shape이 implements하고 있는 Cloneable에서
// clone()을 끌어 온 것
// clone은 this를 복사해서 리턴한다!!!
return circle;
}
}
package Prototype;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Circle c1 = new Circle(1, 1, 2);
Circle c2 = c1.copy(); // copy는 Circle을 리턴한다
System.out.println("c1");
System.out.println(" x : " + c1.getX());
System.out.println(" y : " + c1.getY());
System.out.println(" r : " + c1.getR());
System.out.println("c2");
System.out.println(" x : " + c2.getX());
System.out.println(" y : " + c2.getY());
System.out.println(" r : " + c2.getR());
} // main end
} // class end