Prototype pattern
Encyclopedia
The prototype pattern is a creational design pattern
Design pattern (computer science)
In software engineering, a design pattern is a general reusable solution to a commonly occurring problem within a given context in software design. A design pattern is not a finished design that can be transformed directly into code. It is a description or template for how to solve a problem that...

 used in software development
Software development
Software development is the development of a software product...

 when the type of object
Object (computer science)
In computer science, an object is any entity that can be manipulated by the commands of a programming language, such as a value, variable, function, or data structure...

s to create is determined by a prototypical
Prototype
A prototype is an early sample or model built to test a concept or process or to act as a thing to be replicated or learned from.The word prototype derives from the Greek πρωτότυπον , "primitive form", neutral of πρωτότυπος , "original, primitive", from πρῶτος , "first" and τύπος ,...

 instance, which is cloned to produce new objects. This pattern is used to:
  • avoid subclasses of an object creator in the client application, like the abstract factory pattern
    Abstract factory pattern
    The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...

     does.
  • avoid the inherent cost of creating a new object in the standard way (e.g., using the 'new' keyword) when it is prohibitively expensive for a given application.


To implement the pattern, declare an abstract base class that specifies a pure virtual clone method. Any class that needs a "polymorphic constructor
Constructor (computer science)
In object-oriented programming, a constructor in a class is a special type of subroutine called at the creation of an object. It prepares the new object for use, often accepting parameters which the constructor uses to set any member variables required when the object is first created...

" capability derives itself from the abstract base class, and implements the clone operation.

The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls the clone method on the prototype, calls a factory method with a parameter
Parameter
Parameter from Ancient Greek παρά also “para” meaning “beside, subsidiary” and μέτρον also “metron” meaning “measure”, can be interpreted in mathematics, logic, linguistics, environmental science and other disciplines....

 designating the particular concrete derived class desired, or invokes the clone method through some mechanism provided by another design pattern.

Structure

Example

The Prototype pattern specifies the kind of objects to create using a 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. The mitotic division
Mitosis
Mitosis is the process by which a eukaryotic cell separates the chromosomes in its cell nucleus into two identical sets, in two separate nuclei. It is generally followed immediately by cytokinesis, which divides the nuclei, cytoplasm, organelles and cell membrane into two cells containing roughly...

 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 genotype result. In other words, the cell clones itself.

Java



/**
* Prototype class
*/
abstract class Prototype implements Cloneable {
@Override
public Object clone throws CloneNotSupportedException {
return super.clone;
}

public abstract void setX(int x);

public abstract void printX;

public abstract int getX;
}

/**
* Implementation of prototype class
*/
class PrototypeImpl extends Prototype {
int x;

public PrototypeImpl(int x) {
this.x = x;
}

public void setX(int x) {
this.x = x;
}

public void printX {
System.out.println("Value :" + x);
}

public int getX {
return x;
}
}

/**
* Client code
*/
public class PrototypeTest {
public static void main(String args[]) throws CloneNotSupportedException {
Prototype prototype = new PrototypeImpl(1000);

for (int i=1;i<10;i++) {
Prototype tempotype = (Prototype) prototype.clone;

// Usage of values in prototype to derive a new value.
tempotype.setX( tempotype.getX * i);
tempotype.printX;
}
}
}

/*
    • Code output**


Value :1000
Value :2000
Value :3000
Value :4000
Value :5000
Value :6000
Value :7000
Value :8000
Value :9000

Rules of thumb

Sometimes creational pattern
Creational pattern
In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or added complexity to the design. Creational design...

s overlap - there are cases when either Prototype or Abstract Factory
Abstract factory pattern
The abstract factory pattern is a software design pattern that provides a way to encapsulate a group of individual factories that have a common theme. In normal usage, the client software creates a concrete implementation of the abstract factory and then uses the generic interfaces to create the...

 would be appropriate. At other times they complement each other: Abstract Factory might store a set of Prototypes from which to clone and return product objects (GoF, p126). Abstract Factory, Builder
Builder pattern
The builder pattern is an object creation software design pattern. The intention is to abstract steps of construction of objects so that different implementations of these steps can construct different representations of objects...

, and Prototype can use Singleton
Singleton pattern
In software engineering, the singleton pattern is a design pattern used to implement the mathematical concept of a singleton, by restricting the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system...

 in their implementations. (GoF, p81, 134).
Abstract Factory classes are often implemented with Factory Methods (creation through inheritance
Inheritance (computer science)
In object-oriented programming , inheritance is a way to reuse code of existing objects, establish a subtype from an existing object, or both, depending upon programming language support...

), but they can be implemented using Prototype (creation through delegation
Delegation (programming)
In object-oriented programming, there are two related notions of delegation.* Most commonly, it refers to a programming language feature making use of the method lookup rules for dispatching so-called self-calls as defined by Lieberman in his 1986 paper "Using Prototypical Objects to Implement...

). (GoF, p95)

Often, designs start out using Factory Method (less complicated, more customizable, subclasses proliferate) and evolve toward Abstract Factory, Prototype, 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 initialization. (GoF, p116)

Designs that make heavy use of the Composite
Composite pattern
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes that a group of objects are to be treated in the same way as a single instance of an object. The intent of a composite is to "compose" objects into tree structures to represent...

 and Decorator
Decorator pattern
In object-oriented programming, the decorator pattern is a design pattern that allows behaviour to be added to an existing object dynamically.-Introduction:...

patterns often can benefit from Prototype as well. (GoF, p126)

The rule of thumb could be that you would need to clone an Object when you want to create another Object at runtime which is a true copy of the Object you are cloning. True copy means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have instantiated the class by using new instead, you would get an Object with all attributes as their initial values.
For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object which holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone instead of new.
The source of this article is wikipedia, the free encyclopedia.  The text of this article is licensed under the GFDL.
 
x
OK