From Wikibooks, open books for an open world
Jump to: navigation, search

Factory method Computer Science Design Patterns

The prototype pattern is used when the type of objects to create is determined by a prototypical 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 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" 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 designating the particular concrete derived class desired, or invokes the clone() method through some mechanism provided by another design pattern.


UML class diagram describing the Prototype design pattern

Rules of thumb

Sometimes creational patterns overlap — there are cases when either Prototype or Abstract Factory 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, and Prototype can use Singleton in their implementations. (GoF, p81, 134). Abstract Factory classes are often implemented with Factory Methods (creation through inheritance), but they can be implemented using Prototype (creation through delegation). (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 and Decorator 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 that 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 that 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.


  • Put the prototype term in the name of the prototype classes to indicate the use of the pattern to the other developers.
  • Only use an interface when it is necessary.


It 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 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.

Implementation in C#
//Note: In this example ICloneable interface (defined in .Net Framework) acts as Prototype

class ConcretePrototype : ICloneable
    public int X { get; set; }

    public ConcretePrototype(int x)
        this.X = x;

    public void PrintX()
        Console.WriteLine("Value :" + X);

    public object Clone()
        return this.MemberwiseClone();

 * Client code
public class PrototypeTest
    public static void Main()
        var prototype = new ConcretePrototype(1000);

        for (int i = 1; i < 10; i++)
            ConcretePrototype tempotype = prototype.Clone() as ConcretePrototype;

            // Usage of values in prototype to derive a new value.
            tempotype.X *= i;

 **Code output**

Value :1000
Value :2000
Value :3000
Value :4000
Value :5000
Value :6000
Value :7000
Value :8000
Value :9000
Implementation in C++
#include <iostream>

using namespace std;

// Prototype
class Prototype
    virtual ~Prototype() { }
    virtual Prototype* clone() const = 0;

    virtual void setX(int x) = 0;
    virtual int getX() const = 0;
    virtual void printX() const = 0;
// Concrete prototype
class ConcretePrototype : public Prototype
    ConcretePrototype(int x) : x_(x) { }
    ConcretePrototype(const ConcretePrototype& p) : x_(p.x_) { }
    virtual ConcretePrototype* clone() const { return new ConcretePrototype(*this); }
    void setX(int x) { x_ = x; }
    int getX() const { return x_; }
    void printX() const { std::cout << "Value :" << x_ << std::endl; }
    int x_;
// Client code
int main()
    Prototype* prototype = new ConcretePrototype(1000);
    for (int i = 1; i < 10; i++) {
        Prototype* temporaryPrototype = prototype->clone();
        temporaryPrototype->setX(temporaryPrototype->getX() * i);
        delete temporaryPrototype;
    delete prototype;
    return 0;

Code output:

Value :1000
Value :2000
Value :3000
Value :4000
Value :5000
Value :6000
Value :7000
Value :8000
Value :9000
Implementation in Java
 1 /**
 2  * Prototype class
 3  */
 4 interface Prototype extends Cloneable {
 5     void setX(int x);
 7     void printX();
 9     int getX();
10 }
 1 /**
 2  * Implementation of prototype class
 3  */
 4 class PrototypeImpl implements Prototype {
 5     private int x;
 7     /**
 8      * Constructor
 9      */
10     public PrototypeImpl(int x) {
11         setX(x);
12     }
14     @Override
15     public void setX(int x) {
16         this.x = x;
17     }
19     @Override
20     public void printX() {
21         System.out.println("Value: " + getX());
22     }
24     @Override
25     public int getX() {
26         return x;
27     }
29     @Override
30     public PrototypeImpl clone() throws CloneNotSupportedException {
31         return (PrototypeImpl) super.clone();
32     }
33 }
 1 /**
 2  * Client code
 3  */
 4 public class PrototypeTest {
 5     public static void main(String args[]) throws CloneNotSupportedException {
 6         PrototypeImpl prototype = new PrototypeImpl(1000);
 8         for (int y = 1; y < 10; y++) {
 9             // Create a defensive copy of the object to allow safe mutation
10             Prototype tempotype = prototype.clone();
12             // Derive a new value from the prototype's "x" value
13             tempotype.setX(tempotype.getX() * y);
14             tempotype.printX();
15         }
16     }
17 }

Code output:

Value: 1000
Value: 2000
Value: 3000
Value: 4000
Value: 5000
Value: 6000
Value: 7000
Value: 8000
Value: 9000
Implementation in PHP
class ConcretePrototype {
    protected $x;

    public function __construct($x) {
        $this->x = (int) $x;
    public function printX() {
        echo sprintf('Value: %5d' . PHP_EOL, $this->x);
    public function setX($x) {
        $this->x *= (int) $x;

    public function __clone() {
         * This method is not required for cloning, although when implemented,
         * PHP will trigger it after the process in order to permit you some
         * change in the cloned object.
         * Reference:
        // $this->x = 1;

 * Client code
$prototype = new ConcretePrototype(1000);
foreach (range(1, 10) as $i) {
    $tempotype = clone $prototype;

 **Code output**

Value:  1000
Value:  2000
Value:  3000
Value:  4000
Value:  5000
Value:  6000
Value:  7000
Value:  8000
Value:  9000
Value: 10000
Implementation in Python

This implementation uses the decorator pattern.

# Decorator class which allows an object to create an exact duplicate of itself
class Prototype:    
    def _clone_func(self):
        # This function will be assigned to the decorated object and can
        # be used to create an exact duplicate of that decorated object
        clone = self.cls()
        # Call _copy_func to ensure the attributes of the objects are identical
        self._copy_func(self.instance, clone)
        return clone
    def _copy_func(self, fromObj, toObj):
        # Dual purpose function which is assigned to the decorated object 
        # and used internally in the decorator to copy the original attributes 
        # to the clone to ensure it's identical to the object which made the clone        
        for attr in dir(fromObj):
            setattr(toObj, attr, getattr(fromObj, attr))
    def __init__(self, cls):
        # This is only called once per decorated class type so self.cls 
        # should remember the class that called it so it can generate
        # unique objects of that class later on (in __call__)
        self.cls = cls
    # NOTE: on a decorator "__call__" MUST be implemented
    # this function will automatically be called each time a decorated
    # object is cloned/created
    def __call__(self):
        # Create an instance of the class here so a unique object can be 
        # sent back to the constructor
        self.instance = self.cls()
        # Assign the private functions back to the unique class 
        # (which is the whole point of this decorator)
        self.instance.Clone = self._clone_func
        self.instance.Copy = self._copy_func
        # Finally, send the unique object back to the object's constructor
        return self.instance        

class Concrete:
    def __init__(self):
        # Test value to see if objects are independently generated as
        # well as if they properly copy from one another
        self.somevar = 0
class another:
    def __init__(self):
        self.somevar = 50

if __name__ == '__main__':
    print "Creating A"
    a = Concrete()
    print "Cloning A to B"
    b = a.Clone()
    print "A and B somevars"
    print a.somevar
    print b.somevar
    print "Changing A somevar to 10..."
    a.somevar = 10
    print "A and B somevars"
    print a.somevar
    print b.somevar
    print "Creating another kind of class as C"
    c = another()
    print "Cloning C to D"
    d = c.Clone()
    print "Changing C somevar to 100"
    c.somevar = 100
    print "C and D somevars"
    print c.somevar
    print d.somevar


Creating A
Cloning A to B
A and B somevars
Changing A somevar to 10...
A and B somevars
Creating another kind of class as C
Cloning C to D
Changing C somevar to 100
C and D somevars


To do:
Add more examples of use.

Factory method Computer Science Design Patterns

You have questions about this page?
Ask it here:

Create a new page on this book: