원본출처 : http://home.earthlink.net/~huston2/dp/prototype.html
Prototype
Intent
- Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype. [GoF, p117]
( prototypical? instance을 사용하여 생성될 객체의 종류를 지정한다. 그리고 새로운 객체를 생성 할 때는 이 프로토타입을 카피하여 생성한다. )
- Co-opt one instance of a class for use as a breeder of all future instances. [Amsterdam, p26]
( 이후에 생성될 모든 인스턴스의 종축(번식,근본)으로서 하나의 인스턴스. )
- The
newoperator considered harmful.
( new는 안좋다.)
Problem
Application “hard wires” the class of object to create in each “new” expression
( new를 많이 써서 않좋다는거? ) .
Structure Summary

Structure category: promote X to “full object status”
Similar patterns: Command Iterator Mediator Memento
( 1) 상속 구조에서 clone() 메소드를 선언하고, 하위 클래스에서 구현한다. )
( 2) 각각의 하위 클래스 구현에서는 new 의 사용을 캡슐화 하고 자신의 인스턴스를 리턴한다. )
( 3) 클라이언트는 계층구조의 인스턴스가 필요하면 언제든지 Prototype object에게 위임한다. )
Discussion
Declare an abstract base class that specifies a pure virtual “clone” method, and, maintains a dictionary of all “cloneable” concrete derived classes.
( 추상 베이스 클래스에 순수 가상함수 “clone”을 선언하고 , 모든 “cloneable”한 구체 유도 클래스의 딕셔너리를 유지한다. )
Any class that needs a “polymorphic constructor” capability: derives itself from the abstract base class, registers its prototypical instance, and implements the clone() operation.
( polymorphic constructor가 필요한 클래스는. 그 베이스 클래스를 상속받고, prototypical instance 를 등록하고, clone() 연산자를 구현한다. )
The client then, instead of writing code that invokes the “new” operator on a hard-wired class name, calls a “clone” operation on the abstract base class, supplying a string or enumerated data type that designates the particular concrete derived class desired.
( 이제 클라이언트는 클래스 네임을 앞에 new 연산자를 사용한 하드코딩틱한 코드를 작성하는 대신에, 추상 베이스 클래스에 clone 함수를 호출하여. 그 클래스의 유도 클래스의 인스턴스를 생성할 수 있다.)
Structure

The Factory knows how to find the correct Prototype, and each Product knows how to spawn new instances of itself.
( Factory는 어떻게 적절한 Prototype을 찾는지 안다. 그리고 각 Product는 어떻게 자신의 새로운 인스턴스를 생성하는지 안다. )

Example
The Prototype pattern specifies the kind of objects to create using a prototypical instance.
( Prototype 패턴은 prototypical instance을 사용하여 생성하는 객체의 종류를 지정한다. )
Prototypes of new products are often built prior to full production, but in this example, the prototype is passive and does not participate in copying itself.
( 새로운 제품의 Prototypes은 제품 완성 이전에 구축되지만, 이번 예제에서는 prototype은 수동적(passive?) 이고 자신을 복사하는데 참여하지 않는다. )
The mitotic division of a cell – resulting in two identical cells – is an example of a prototype that plays an active role in copying itself and thus, demonstrates the Prototype pattern.
( 세포의 유사분열 – 결과로 남게되는 두개의 세포 – 는 프로토타입의 예이다. )
When a cell splits, two cells of identical genotvpe result.
( 세포가 분열될 때, 두개의 세포가 남는다. )
In other words, the cell clones itself.
( 다른 말로, 세포는 클론된다. 복제도니다. )
[Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

example–>
Check list
- Add a
clone()method to the existing “product” hierarchy. - Design a “registry” that maintains a cache of prototypical objects. The registry could be encapsulated in a new
Factoryclass, or in the base class of the “product” hierarchy. - Design a factory method that: may (or may not) accept arguments, finds the correct prototype object, calls
clone()on that object, and returns the result. - The client replaces all references to the
newoperator with calls to the factory method.
( 1. ”제품” 계층구조에 clone() 메소드를 추가한다. )
( 2. prototypical objects를 캐싱하여 관리하는 “registry”를 디자인한다. registery는 새로운 factory class에 캡슐화 되거나, “제품” 계층구조의 베이스 클래스에 캡슐화 돌 수도 있다. )
( 3. 매개변수를 받고(아니거나), 적절한 프로토타입 객체를 찾고, 그 객체에 clone()을 호출하고, 그 결과를 리턴하는 factory method를 디자인한다. )
( 4. 클라이언트는 factory method를 호출함으로써 new 연산자를 사용해야 하는 필요를 대체 한다. )
// A clone() method has been added to the Stooge
// hierarchy. Each derived class implements that
// method by returning an instance of itself. A
// Factory class has been introduced that main-
// tains a suite of “breeder” objects (aka proto-
// types), and knows how to delegate to the
// correct prototype.
class Stooge {
public:
virtual Stooge* clone() = 0;
virtual void slap_stick() = 0;
};
class Factory {
public:
static Stooge* make_stooge( int choice );
private:
static Stooge* s_prototypes[4];
};
int main( void ) {
vector roles;
int choice;
while (true) {
cout << “Larry(1) Moe(2) Curly(3) Go(0): “;
cin >> choice;
if (choice == 0)
break;
roles.push_back(
Factory::make_stooge( choice ) );
}
for (int i=0; i < roles.size(); ++i)
roles[i]->slap_stick();
for (int i=0; i < roles.size(); ++i)
delete roles[i];
}
class Larry : public Stooge {
public:
Stooge* clone() { return new Larry; }
void slap_stick() {
cout << “Larry: poke eyes\n”; }
};
class Moe : public Stooge {
public:
Stooge* clone() { return new Moe; }
void slap_stick() {
cout << “Moe: slap head\n”; }
};
class Curly : public Stooge {
public:
Stooge* clone() { return new Curly; }
void slap_stick() {
cout << “Curly: suffer abuse\n”; }
};
Stooge* Factory::s_prototypes[] = {
0, new Larry, new Moe, new Curly
};
Stooge* Factory::make_stooge( int choice ) {
return s_prototypes[choice]->clone();
}
Rules of thumb
Sometimes creational patterns are competitors: there are cases when either Prototype or Abstract Factory could be used properly. At other times they are complementory: Abstract Factory might store a set of Prototypes from which to clone and return product objects [GOF, p126]. Abstract Factory, Builder, and Prototype can use Singleton in their implementations. [GoF, p81, 134].
Abstract Factory classes are often implemented with Factory Methods, but they can be implemented using Prototype. [GoF, p95]
Factory Method: creation through inheritance. Protoype: creation through delegation.
Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Protoype, or Builder (more flexible, more complex) as the designer discovers where more flexibility is needed. [GoF, p136]
Prototype doesn’t require subclassing, but it does require an “initialize” operation. Factory Method requires subclassing, but doesn’t require Initialize. [GoF, p116]
Designs that make heavy use of the Composite and Decorator patterns often can benefit from Prototype as well. [GoF, p126]
Prototype co-opts one instance of a class for use as a breeder of all future instances. [Amsterdam, p26]
Prototypes are useful when object initialization is expensive, and you anticipate few variations on the initialization parameters. In this context, Prototype can avoid expensive “creation from scratch”, and support cheap cloning of a pre-initialized prototype. [Amsterdam, p26]
Prototype is unique among the other creational patterns in that it doesn’t require a class – only an object. Object-oriented languages like Self and Omega that do away with classes completely rely on prototypes for creating new objects. [Amsterdam, p26]