728x90
클래스들에 의존시키지 않고 기존 객체들을 복사할 수 있도록 도와주는 디자인 패턴입니다.
생성 패턴(Creational Design Patterns) 중 하나입니다.
장점
- 객체들을 구상 클래스들에 결합하지 않고 복제할 수 있습니다.
- 초기화 코드를 대신 만들어진 프로토타입을 복제하 사용할 수 있습니다.
- 복잡한 객체들을 쉽게 생성할 수 있습니다.
- 사전 정보들을 처리할 때 상속 대신 사용할 수 있니다.
단점
- 순환 참조가 있는 복잡한 객체를 복제하는 경우 귀찮습니다.
C#으로 Console 프로젝트를 하나 생성해서 할 것입니다.
이번엔 Animal과 Bottle을 생성하고 복제하겠습니다.
일단 프로젝트의 tree구조는 아래와 같습니다.
Prototype(Project)
|- Program.cs (Main)
|- IObject.cs (Prototype Interface)
|- Animal.cs (Concrete Prototype)
|- Bottle.cs (Concrete Prototype)
IObject.cs
namespace Prototype
{
public interface IObject
{
IObject Clone();
}
}
복제를 위한 Clone Method를 구성해줍니다.
Animal.cs
namespace Prototype
{
public class Animal : IObject
{
public string name { get; set; }
public int age { get; set; }
public IObject Clone()
{
return new Animal() { name = this.name, age = this.age };
}
}
}
이름과 나이를 만들고 IObject의 Clone을 구현해줍니다. 가지고있는 속성을 복사해서 새로 만들어 return!
Bottle.cs
using System;
namespace Prototype
{
public class Bottle : IObject
{
public DateTime MFG { get; set; }
public string color { get; set; }
public IObject Clone()
{
return new Bottle() { MFG = this.MFG, color = this.color };
}
}
}
제조일과 색 필드를 만들어 줍니다.
그리고 IObject의 Clone을 구현!
Program.cs
using System;
namespace Prototype
{
class Program
{
static void Main(string[] args)
{
Bottle blueBottle = new Bottle();
blueBottle.MFG = DateTime.Now;
blueBottle.color = "blue";
Animal animal = new Animal();
animal.age = 3;
animal.name = "kei";
Console.WriteLine($"[blueBottle] MFG: {blueBottle.MFG} / Color: {blueBottle.color}");
Console.WriteLine($"[animal] Age: {animal.age} / Name: {animal.name}");
Console.WriteLine();
Bottle blueBottle_c = (Bottle) blueBottle.Clone();
Animal animal_c = (Animal) animal.Clone();
Console.WriteLine($"[blueBottle(Clone)] MFG: {blueBottle_c.MFG} / Color: {blueBottle_c.color}");
Console.WriteLine($"[animal(Clone)] Age: {animal_c.age} / Name: {animal_c.name}");
}
}
}
Bottle을 만들고 제조일과 색을 설정합니다.
Animal의 경우에도 이름과 나이를 설정해준뒤
각 정보들을 출력해줍니다.
이제 생성해놓은 친구들을 Clone해서
정보를 출력해봅니다,
원본과 동일한 결과로 복사가 잘됐음을 확인할 수 있습니다.
DeepCopy가 자주 필요한 객체에서 쓰일 수 있는 패턴입니다.
유용하게 사용하시면 좋을거 같습니다.
'Design Pattern' 카테고리의 다른 글
[Design Pattern] 24. Interpreter Pattern(인터프리터 패턴) C# (1) | 2023.04.13 |
---|---|
[Design Pattern] 23. Builder Pattern(빌더 패턴) C# (0) | 2023.04.12 |
[Design Pattern] 21. Abstract Factory Pattern(추상 팩토리 패턴) C# (0) | 2023.04.10 |
[Design Pattern] 20. Factory Method Pattern(팩토리 메소드 패턴) C# (0) | 2023.04.09 |
[Design Pattern] 19. Singleton Pattern(싱글톤 패턴) C# (0) | 2023.04.08 |