프로토타입 패턴은 저장된 프로토타입들 중 하나를 복제 하여 새로움 객체를 생성한다.
장점 : 크고 동적 로드 클래스의 빠른 인스턴스화가 가능 , 생성한 서브클래스를 몰라도 그들의 식별 정보를 유지
- 주의점 Clone 의 기능 구현 , Shallow Copy Deep Copy 차이, MemberwiseClone, Serialization 차이
구현 언어나 사용 라이브러리에 따라 Clone 기능 차이 있을수 있음.
namespace PrototypePattern
{
[Serializable()]
public abstract class IPrototype<T>
{
// Shallow copy
public T Clone()
{
return (T)MemberwiseClone();
}
// Deep Copy
public T DeepCopy()
{
MemoryStream stream = new MemoryStream();
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, this);
stream.Seek(0, SeekOrigin.Begin);
T copy = (T)formatter.Deserialize(stream);
stream.Close();
return copy;
}
}
[Serializable()]
// Helper class used to create a second level data structure
class DeeperData
{
public string Data { get; set; }
public DeeperData(string s)
{
Data = s;
}
public override string ToString()
{
return Data;
}
}
[Serializable()]
class Prototype : IPrototype<Prototype>
{
// Content members
public string Country { get; set; }
public string Capital { get; set; }
public DeeperData Language { get; set; }
public Prototype(string country, string capital, string language)
{
Country = country;
Capital = capital;
Language = new DeeperData(language);
}
public override string ToString()
{
return Country + "\t\t" + Capital + "\t\t->" + Language;
}
}
class PrototypeManager
{
public Dictionary<string, Prototype> prototypes = new Dictionary<string, Prototype>
{
{"Germany", new Prototype ("Germany", "Berlin", "German")},
{ "Italy", new Prototype ("Italy", "Rome", "Italian")},
{ "Australia", new Prototype ("Australia", "Canberra", "English")}
};
}
class Program
{
static void Report(string s, Prototype a, Prototype b)
{
Console.WriteLine("\n" + s);
Console.WriteLine("Prototype " + a + "\nClone " + b);
}
static void Main(string[] args)
{
PrototypeManager manager = new PrototypeManager();
Prototype c2, c3;
c2 = manager.prototypes["Australia"].Clone();
Report("Shallow cloning Australia\n===============", manager.prototypes["Australia"], c2);
c2.Capital = "Sydney";
Report("Altered Clone's shallow state, prototype unaffected", manager.prototypes["Australia"], c2);
c2.Language.Data = "Chinese";
Report("Altering Clone deep state: prototype affected *****", manager.prototypes["Australia"], c2);
c3 = manager.prototypes["Germany"].DeepCopy();
Report("Deep cloning Germany\n============", manager.prototypes["Germany"], c3);
c3.Capital = "Munich";
Report("Altering Clone shallow state, prototype unaffected",manager.prototypes["Germany"], c3);
c3.Language.Data = "Turkish";
Report("Altering Clone deep state, prototype unaffected", manager.prototypes["Germany"], c3);
}
}
}
'Programming' 카테고리의 다른 글
RSS Feed를 가져오는 C# 예제를 통한 Async 효율성 테스트 (0) | 2017.04.11 |
---|---|
Factory Method Pattern (0) | 2016.10.15 |
우분투 (Ubuntu 16.04) 에 JAVA 설치 (0) | 2016.07.31 |
변화된 모던 C++, 심층분석 - 불어오는 변화의 바람 C++98 to C++11/14 (0) | 2016.01.01 |
Regular expressions 정규표현 식 (3) | 2015.09.28 |