반응형

디자인 패턴들

    Purpose
    Defer Object creation to another class or object Describe ways to assemble objects Address problems of assigning responsibilities
    Creational (생성) Structural (구조) Behavioral (행동)
Scope Class Factory Method Adapter Interpreter
Template
Object Abstract Factory
Builder
Prototype
Singleton
Adapter
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
CoR
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor

 

 Prototype 패턴은, clone 메서드를 활용해서, 객체를 생성합니다.

각 서브클래스들은 new를 사용하지 않습니다.

Prototype 패턴이란?

이 패턴은,

생성할 객체들의 타입이 떤 특정 객체 (프로토타입인 인스턴스)로 부터 결정되기 위해서 사용합니다.

해당, 프로토타입인 인스턴스새 객체를 만들기 위해서, 자신을 복제(clone)합니다.

 

 우린, 평소에 new를 이용해서 객체를 생성해 왔다. 하지만, 이 패턴은 오직 프로토타입인 인스턴스의 clone메서드를 이용해서만, 객체를 생성한다. 즉, 객체의 생성을 특정 인스턴스의 clone 메서드를 이용해서만 생성한다는 뜻이다.

 

성질 1. new를 이용하여, 객체를 생성하지 않고, 인스턴스의 clone()을 이용해서, 객체를 만든다.

왜 이 패턴을 쓰는가?

장점 1. 성질 1에 의해, new를 이용한 비용을 줄일 수 있다. (객체 생성 비용이 응용프로그램 상황에 있어서, 매우 클 때)

장점 2. 객체 창조자(creater)를 서브스클래스(subclass)하는 것을 피할 수 있게 해준다.

 

원칙

원칙 1. 런타임에 또 다른 객체를 생성한다. 이 시점에서 클로닝(cloning)을 하는 객체의 실제 복사본이 만들어진다.

즉, 클로닝 당하는 객체의 애튜리뷰트와 똑같은 애트리뷰트를 가질 것이다.

(만약, new를 사용했으면, 애튜리뷰트는 초기값을 가질 것이다)

 

코드 (Java)

/** Prototype Class **/
public class Cookie implements Cloneable {

   public Object clone() {
      try {
         Cookie copy = (Cookie)super.clone();

         //In an actual implementation of this pattern you might now change references to
         //the expensive to produce parts from the copies that are held inside the prototype.

         return copy;

      }
      catch(CloneNotSupportedException e) {
         e.printStackTrace();
         return null;
      }
   }
}

/** Concrete Prototypes to clone **/
public class CoconutCookie extends Cookie { }

/** Client Class**/
public class CookieMachine {

   private Cookie cookie;//could have been a private Cloneable cookie;

   public CookieMachine(Cookie cookie) {
      this.cookie = cookie;
   }
   public Cookie makeCookie() {
      return (Cookie)cookie.clone();
   }
   public Object clone() { }

   public static void main(String args[]) {
      Cookie tempCookie =  null;
      Cookie prot = new CoconutCookie();
      CookieMachine cm = new CookieMachine(prot);
      for (int i=0; i<100; i++)
         tempCookie = cm.makeCookie();
   }
}

 

출처/인용자료

위키백과 https://ko.wikipedia.org/wiki/%ED%94%84%EB%A1%9C%ED%86%A0%ED%83%80%EC%9E%85_%ED%8C%A8%ED%84%B4

반응형