STUDY/Design Pattern
원형 패턴 (Prototype Pattern)
디리릭
2022. 11. 27. 20:44
728x90
프로토타입 패턴은 자기 자신을 복제함으로써 새 객체를 생성한다. 이때 복제 방식은 Shallow copy 방식이다.
구조

▷ Prototype: 자기 자신을 복제하는데 필요한 인터페이스
▷ ConcretePrototype: 자기 자신을 복제하는 것을 구현하는 클래스
구현
abstract class Prototype
{
public abstract Prototype Clone();
}
class Patient : Prototype
{
public string name;
public string ptNo;
public string dept;
public string docName;
public Patient(string name, string ptNo, string dept, string docName)
{
this.name = name;
this.ptNo = ptNo;
this.dept = dept;
this.docName = docName;
}
public override Prototype Clone()
{
return (Prototype)this.MemberwiseClone();
}
}
static void Main(string[] args)
{
var pt1 = new Patient("아귀","111111","치과","강냉이컬렉터");
var pt2 = pt1.Clone();
Console.WriteLine($"pt1 이름 -> {pt1.name}/ pt2 이름 -> {((Patient)pt2).name}");
pt1.name = "고니";
Console.WriteLine($"pt1 이름 -> {pt1.name}/ pt2 이름 -> {((Patient)pt2).name}");
var pt3 = new Patient("김사부", "2222222", "외과", "장첸");
var pt4 = pt3;
Console.WriteLine($"pt3 이름 -> {pt3.name}/ pt4 이름 -> {pt4.name}");
pt4.name = "최사부";
Console.WriteLine($"pt3 이름 -> {pt3.name}/ pt4 이름 -> {pt4.name}");
}

Deep copy와 Shallow copy의 차이점은 전 회사에서 프로젝트를 하다가 알게 되었다.
이미 정의된 객체를 복제하기 위해
새 객체 = 이미 존재한 객체 <<< 이렇게 등호로 복제를 했더니
새 객체의 변화가 이미 존재한 객체도 동일하게 변하는것이다. 이것떄문에 버그가 생겻었지 ....
위와 같이 등호로 객체를 복사하는 것은 Deep copy에 속한다.
즉 구성 뿐만 아니라 주소값도 복사되어 새객체와 이미 존재한 객체가 연동되는것이다.
=> 나와 똑같은 클론들을 만드는 것인 목적
728x90