본문 바로가기

Language/Design Pattern

[Desigon Pattern: 생성] 4. Prototype

목적

객체를 생성할때에는 new 를 사용한다. 이 연산은 비용이 큰 연산이고, 생성할때의 로직이 복잡하다면 더욱 더 비용은 증가할 것이다.

따라서, 이를 최소화하기 위해 clone(복사)를 통해 이 비용을 줄이기 위핸 패턴이다.


예제

스타크래프트를 통해 예제 코드를 작성했다.

하지만 아래의 예제코드는 목적이 Prototype에는 확실히 부합하지 않는다. 유닛의 객체 생성의 과정이 굉장히 복잡하다고 가정하고 아래와 같은 예제 코드를 작성하였다. 

Prototype을 쓰는 방식은 맞기 때문에 쉽게 사용방법을 이해하는 목적으로 봐주시길...


기본적으로 Unit이란 Abstraction에 Cloneable을 implements했다. 이를 통해 Clone(복사)가 가능하다.

이 Unit을 상속받아 만든 Tank!! Goliath이 있다. 원래는 많은 정보가 담기겠지만 지금은 Attack()함수만 구현했다.


탱크, 골리앗을 만들 수 있는 Factory이다. Prototype으로 만들었기 때문에 최초 복사할 객체를 등록하는 register()함수와 객체를 실제로 생성(내부적으로 복사지만..)하는 createClone()함수로 구성


자 이제 factory를 통해서 탱크와 골리앗을 만든다.

최초 생성한 탱크와 골리앗을 등록하고, 등록한 이름(key)으로 다시 생성해서 사용하면 끝!

쉽다. 하지만 왜, 어떤 목적으로 사용하는 것이 더 중요하기 때문에 개념을 잡는 것이 중요한듯 하다.


이래를 돕기위한 다른 예제 코드

<다른 예제>

01public interface Product extends Cloneable {
02    public abstract void use(String s);
03    public abstract Product createClone();
04}
05 
06public class MessageBox implements Product {
07    private char decochar;
08     
09    public MessageBox(char decochar) {
10        this.decochar = decochar;
11    }  
12     
13    public void use(String s) {
14        int length = s.getBytes().length;
15        for (int i = 0; i < length + 4; i++) {
16            System.out.print(decochar);
17        }
18        System.out.println("");
19        System.out.println(decochar + " " + s + " " + decochar);
20        for (int i = 0; i < length + 4; i++) {
21            System.out.print(decochar);
22        }
23        System.out.println(" ");
24    }
25 
26    public Product createClone() {
27        Product p = null;
28        try {
29            p = (Product)clone();
30        catch (CloneNotSupportedException e) {
31            e.printStackTrace();
32        }
33        return p;
34    }
35}
36 
37public class Manager {
38    private HashMap showcase = new HashMap();
39     
40    public void register(String name, Product proto) {
41        showcase.put(name, proto);
42    }
43     
44    public Product create(String protoname) {
45        Product p = (Product)showcase.get(protoname);
46        return p.createClone();
47    }
48}
49 
50public class Main {
51    public static void main(String[] args) {
52        Manager manager = new Manager();
53        MessageBox mbox = new MessageBox('*');
54        MessageBox sbox = new MessageBox('/');
55        manager.register("strong message", mbox);
56        manager.register("slash box", sbox);
57         
58        Product p1 = manager.create("strong message");
59        p1.use("Hello world");
60        Product p2 = manager.create("slash box");
61        p2.use("Hello world");
62    }
63}