노현진's Blog

Prototype Pattern

Prototype Pattern에 대해 설명하는 페이지입니다.

Posted
Preview Image
By HyunJinNo

Tags

Design Pattern, Java

1. Introduction

  • Purpose
    • Create objects based upon a template of an existing objects through cloning.
  • Use When
    • Composition, creation, and representation of objects should be decoupled from a system
    • Classes to be created are specified at runtime.
    • Objects or object structures are required that are identical or closely resemble other existing objects or object structures.
    • The initial creation of each object is an expensive operation.
    • When to avoid building a class hierarchy of factories that parallels the class hierarchy of products

2. Characteristics

  • Advantage
    • Hides concrete product classes from clients
    • Decouples the clients from the creational process
  • Prototypes can be supplied and changed at runtime
  • The client asks the prototype to clone itself for a new object of the prototype.
  • It provides great flexibility in configuring and changing a program at runtime
    • Adding and removing products at run-time
    • Reduced subclassing
    • Configuring an application with classes dynamically
      • Loading the classes dynamically

3. Participants

  • Prototype
    • Defines the interface (an operation) of cloning itself.
  • ConcreteProducts
    • Concrete objects that can clone themselves.
  • Client
    • Obtain more objects by asking them to clone themselves.

4. How to Use (Example)

  • Java's Cloneable

    java
    1class Stack implements Cloneable {
    2    private final int maxSize;
    3    private int top;
    4    private Object[] store;
    5
    6    public Stack (int size) {
    7        maxSize = size;
    8        store = new Object[size];
    9        top = -1;
    10    }
    11
    12    public Object clone() throws CloneNotSupportedException {
    13        Stack result;
    14        try {
    15            result = (Stack) super.clone();
    16            result.store = (Object[]) store.clone();
    17            return result;
    18        } catch (CloneNotSupportedException e) {
    19            return null;
    20        }
    21    }
    22}

© HyunJinNo. Some rights reserved.