Next revision | Previous revision |
design_pattern:prototype_pattern [2017/10/27 14:38] – 만듦 ledyx | design_pattern:prototype_pattern [2021/02/07 03:28] (current) – [Prototype Pattern] ledyx |
---|
= Prototype Pattern = | = Prototype Pattern = |
모형이 되는 인스턴스를 복사해서 인스턴스 생성 | * 모형이 되는 인스턴스를 복사해서 인스턴스 생성 |
| * 그러나 Java/C#에서 제공되는 clone() 을 사용하면 얕은 복사(Shallow Copy)가 되므로 클래스 안에 참조 형식의 데이터가 있으면 제대로 복사가 되지 않음. |
| * 직렬화(Serialize)를 이용하여 깊은 복사(Deep Copy) 구현. |
| * 언제 쓰는게 좋을까? |
| * 자주 DB에 접근하여 삽입/삭제/수정하는 데이터인 경우 2Tier가 아닌 중간에 Middleware를 놓고 복사본을 수정하는 게 성능상 이득. (Caching) |
| * 원본 데이터는 그대로 보존이 필요하고, 따로 수정할 데이터가 있는 경우 (ex. 파일 불러오기, 되돌리기) |
| |
https://en.wikipedia.org/wiki/Design_Patterns#Patterns_by_Type | https://en.wikipedia.org/wiki/Design_Patterns#Patterns_by_Type |
| |
{{tag>Architecture Modeling DesignPattern}} | {{tag>Architecture Modeling Design_Pattern Creational}} |
| |
= Java = | = Java = |
| |
== Client == | == Prototype == |
<sxh java> | <sxh java> |
/* 깊은 복사를 위해 Serializable 필요 */ | /* 깊은 복사를 위해 Serializable 필요 */ |
ObjectOutputStream oos = new ObjectOutputStream(baos); | ObjectOutputStream oos = new ObjectOutputStream(baos); |
oos.writeObject(target); | oos.writeObject(target); |
| oos.close(); |
| baos.close(); |
| |
ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); | ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray()); |
ObjectInputStream ois = new ObjectInputStream(bais); | ObjectInputStream ois = new ObjectInputStream(bais); |
| ois.close(); |
| bais.close(); |
| |
return (T) ois.readObject(); | return (T) ois.readObject(); |
} catch (IOException e) { | } catch (IOException e) { |
</sxh> | </sxh> |
| |
== Prototype, ConcretePrototype == | == ConcretePrototype == |
<sxh java ; title: Prototype> | <sxh java> |
/* 깊은 복사를 위해 Serializable 필요 */ | /* 깊은 복사를 위해 Serializable 필요 */ |
public interface Character extends Serializable { | public interface Character extends Serializable { |
} | } |
} | } |
<sxh> | </sxh> |
| |
| |
</sxh> | </sxh> |
| |
== 실행 == | == Client == |
<sxh java> | <sxh java> |
public class Main { | public class Main { |