[생성 패턴] 프로토 타입 (Prototype Parttern)
@Getter
public class Test implements Cloneable{
private String name;
private TestChild testParent;
@Override
public Test clone() throws CloneNotSupportedException {
return (Test) super.clone();
}
public Test(String name, TestChild testParent) {
this.name = name;
this.testParent = testParent;
}
}
@Getter
public class TestDeepCopy implements Cloneable{
private String name;
private TestChild testChild;
public TestDeepCopy(String name, TestChild testChild) {
this.name = name;
this.testChild = testChild;
}
@Override
public TestDeepCopy clone() throws CloneNotSupportedException {
TestChild testChild = new TestChild(this.testChild.getName());
return new TestDeepCopy(this.name, testChild, integer, anInt);
}
}
@Getter
public class TestChild {
private String name;
public TestChild(String name) {
this.name = name;
}
}
public class App {
public static void main(String[] args) throws CloneNotSupportedException {
//**************** super.clone() 얕은 복사 ***********//
TestChild testChild = new TestChild("testchild");
Test test = new Test("test", testChild);
Test testClone = test.clone();
//같은 객체가 아님
System.out.println(test != testClone);
//값 복사
System.out.println(Objects.equals(test.getName(), testClone.getName()));
//객체 얕은 복사
System.out.println(test.getTestParent() == testClone.getTestParent());
//************************************//
//**************** 깊은 복사 ***********//
TestChild testChild1 = new TestChild("testchild1");
TestDeepCopy testDeepCopy = new TestDeepCopy("testDeepCopy", testChild1);
TestDeepCopy testDeepCopy1 = testDeepCopy.clone();
//복사된 객체는 다름
System.out.println(testDeepCopy != testDeepCopy1);
//클래스 내부의 객체도 깊은 복사
System.out.println(testDeepCopy.getTestChild() != testDeepCopy1.getTestChild());
//**************** 깊은 복사 ***********//
}
}
//결과
true
true
true
true
trueLast updated