Observer Computer Science Design Patterns
Prototype
Proxy

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.

Structure

 
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.

Advices

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

Implementations

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#

The concrete type of object is created from its prototype. MemberwiseClone is used in the Clone method to create and return a copy of ConcreteFoo1 or ConcreteFoo2.

public abstract class Foo
{
    // normal implementation

    public abstract Foo Clone();
}

public class ConcreteFoo1 : Foo
{
    public override Foo Clone()
    {
        return (Foo)this.MemberwiseClone(); // Clones the concrete class.
    }
}

public class ConcreteFoo2 : Foo
{
    public override Foo Clone()
    {
        return (Foo)this.MemberwiseClone(); // Clones the concrete class.
    }
}

Another example:

//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;
            tempotype.PrintX();
        }
        Console.ReadKey();
    }
}

/*
 **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
{
public:
    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
{
public:
    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; }
 
private:
    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);
        temporaryPrototype->printX();
        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

This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class creates a clone of it and returns it as prototype. The clone method has been used to clone the prototype when required.

// Prototype pattern
public abstract class Prototype implements Cloneable {
    public Prototype clone() throws CloneNotSupportedException{
        return (Prototype) super.clone();
    }
}
	
public class ConcretePrototype1 extends Prototype {
    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (ConcretePrototype1)super.clone();
    }
}

public class ConcretePrototype2 extends Prototype {
    @Override
    public Prototype clone() throws CloneNotSupportedException {
        return (ConcretePrototype2)super.clone();
    }
}

Another example:

/**
 * Prototype class
 */
interface Prototype extends Cloneable {
    void setX(int x);
   
    void printX();
   
    int getX();
}
/**
 * Implementation of prototype class
 */
class PrototypeImpl implements Prototype {
    private int x;

    /**
     * Constructor
     */
    public PrototypeImpl(int x) {
        setX(x);
    }

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

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

    @Override
    public int getX() {
        return x;
    }

    @Override
    public PrototypeImpl clone() throws CloneNotSupportedException {
        return (PrototypeImpl) super.clone();
    }
}
/**
 * Client code
 */
public class PrototypeTest {
    public static void main(String args[]) throws CloneNotSupportedException {
        PrototypeImpl prototype = new PrototypeImpl(1000);
       
        for (int y = 1; y < 10; y++) {
            // Create a defensive copy of the object to allow safe mutation
            Prototype tempotype = prototype.clone();

            // Derive a new value from the prototype's "x" value
            tempotype.setX(tempotype.getX() * y);
            tempotype.printX();
        }
    }
}

Code output:

Value: 1000
Value: 2000
Value: 3000
Value: 4000
Value: 5000
Value: 6000
Value: 7000
Value: 8000
Value: 9000
Implementation in PHP
// The Prototype pattern in PHP is done with the use of built-in PHP function __clone()

abstract class Prototype
{
    public string $a;
    public string $b;
    
    public function displayCONS(): void
    {
        echo "CONS: {$this->a}\n";
        echo "CONS: {$this->b}\n";
    }
    
    public function displayCLON(): void
    {
        echo "CLON: {$this->a}\n";
        echo "CLON: {$this->b}\n";
    }

    abstract function __clone();
}

class ConcretePrototype1 extends Prototype
{
    public function __construct()
    {
        $this->a = "A1";
        $this->b = "B1";
        
        $this->displayCONS();
    }

    function __clone()
    {
        $this->displayCLON();
    }
}

class ConcretePrototype2 extends Prototype
{
    public function __construct()
    {
        $this->a = "A2";
        $this->b = "B2";
        
        $this->displayCONS();
    }

    function __clone()
    {
        $this->a = $this->a ."-C";
        $this->b = $this->b ."-C";
        
        $this->displayCLON();
    }
}

$cP1 = new ConcretePrototype1();
$cP2 = new ConcretePrototype2();
$cP2C = clone $cP2;

// RESULT: #quanton81

// CONS: A1
// CONS: B1
// CONS: A2
// CONS: B2
// CLON: A2-C
// CLON: B2-C

Another example:

<?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: http://php.net/manual/en/language.oop5.cloning.php
         */
        // $this->x = 1;
    }
}

/**
 * Client code
 */
$prototype = new ConcretePrototype(1000);
 
foreach (range(1, 10) as $i) {
    $tempotype = clone $prototype;
    $tempotype->setX($i);
    $tempotype->printX();
}

/*
 **Code output**

Value:  1000
Value:  2000
Value:  3000
Value:  4000
Value:  5000
Value:  6000
Value:  7000
Value:  8000
Value:  9000
Value: 10000
*/
Implementation in Pseudocode

Let's write an occurrence browser class for a text. This class lists the occurrences of a word in a text. Such an object is expensive to create as the locations of the occurrences need an expensive process to find. So, to duplicate such an object, we use the prototype pattern:

class WordOccurrences is
    field occurrences is
        The list of the index of each occurrence of the word in the text.

    constructor WordOccurrences(text, word) is
            input: the text in which the occurrences have to be found
            input: the word that should appear in the text
        Empty the occurrences list
        for each Template:Not a typo in text
            Template:Not a typog:= true
            for each Template:Not a typo in word
                if the current word character does not match the current text character then
                    Template:Not a typog:= false
            if Template:Not a typo is true then
                Add the current Template:Not a typo into the occurrences list

    method getOneOccurrenceIndex(n) is
            input: a number to point on the nth occurrence.
            output: the index of the nth occurrence.
        Return the nth item of the occurrences field if any.

    method clone() is
            output: a WordOccurrences object containing the same data.
        Call clone() on the super class.
        On the returned object, set the occurrences field with the value of the local occurrences field.
        Return the cloned object.

texte:= "The prototype pattern is a creational design pattern in software development first described in design patterns, the book."
wordw:= "pattern"d
searchEnginen:= new WordOccurrences(text, word)
anotherSearchEngineE:= searchEngine.clone()

(the search algorithm is not optimized; it is a basic algorithm to illustrate the pattern implementation)

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

@Prototype
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
        
@Prototype
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

Output:

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


 

To do:
Add more examples of use.


  Observer Computer Science Design Patterns
Prototype
Proxy  


You have questions about this page?
Ask it here:


Create a new page on this book: