728x90
반응형
생산 비용이 높은 인스턴스를 복사를 통해서 쉽게 생성 할 수 있도록 하는 패턴
왜 비싸 ???
- 종류가 너무 많아서 클래스로 정리되지 않는다
- 클래스로부터 인스턴스 생성이 어렵다.
프로토타입 패턴은 원본 객체를 새로운 객체에 복사하여 필요에 따라 수정하는 메커니즘을 제공한다.

package Prototype;
public class Circle extends Shape {
private int x,y,r;
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();
circle.x +=1;
circle.y +=1; // 두 도형이 안 겹치게 이동
return circle;
}
}
package Prototype;
public class Shape implements Cloneable{
private String id;
public void setId(String id) {
this.id = id;
}
public String getId() {
return id;
}
}
프로토타입 패턴은 원본 객체를 새로운 객체에 복사하여 필요에 따라 수정하는 메커니즘을 제공한다.
cloneable 를 impleents 하고
(Circle)clone 해주면 복사해준다.
깊은복사 / 얇은복사
package Prototype.DeepShallow;
public class Main {
public static void main(String[] args) throws CloneNotSupportedException {
Cat navi = new Cat();
navi.setName("navi");
navi.setAge(new Age(2012,3));
// Cat yo = navi; // 복사
Cat yo = navi.copy(); // 깊은 복사
yo.setName("boseok");
yo.getAge().setValue(2013);
yo.getAge().setValue(2);
//age는 깊은복사가 안됐다. >> 해결방법 Cat 에서 clone 할때 복사시에 바ㄱ
System.out.println("navi = " + navi.getName());
System.out.println("yo.getAge() = " + navi.getAge().getYear());
System.out.println("yo = " + yo.getName());
System.out.println("yo.getAge() = " + yo.getAge().getYear());
System.out.println("navi.getAge().getValue() = " + navi.getAge().getValue());
System.out.println("yo.getAge().getValue() = " + yo.getAge().getValue());
// 같게 나오는 이유 동일한 주소값을 쓴다. navi 에 주솟값을 yo에 가져간다 >> 얕은복사 navi의 값을 주면>> 깊은복사
}
}
package Prototype.DeepShallow;
public class Cat implements Cloneable {
private String name;
private Age age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Age getAge() {
return age;
}
public void setAge(Age age) {
this.age = age;
}
public Cat copy() throws CloneNotSupportedException {
Cat ret = (Cat) this.clone();
ret.setAge(new Age(this.age.getYear(),this.age.getValue()));
return ret;
}
}
자바에서 제공하는 스트링이나,클래스 같은 경우는 깊은복사를 자동으로 주솟값을 변경해서 해주는 기능이있다.
ret.setAge(new Age(this.age.getYear(),this.age.getValue()));
age는 깊은복사가 안된다 >> 해결하려면 고양이 카피하는 곳에서 명시적으로 깊은 복사를 해줘야한다.
반응형
댓글