Prototype pattern

This is an old revision of this page, as edited by AndreAdrian (talk | contribs) at 14:26, 5 May 2023 (Pseudocode: move Pseudocode example to Wikibooks). The present address (URL) is a permanent link to this revision, which may differ significantly from the current revision.

The prototype pattern is a creational design pattern in software development. It 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 factory method pattern does, and to 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, the client declares 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.

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.[1]

Overview

The prototype design pattern is one of the 23 Gang of Four design patterns that describe how to solve recurring design problems to design flexible and reusable object-oriented software, that is, objects that are easier to implement, change, test, and reuse.[2]: 117 

The prototype design pattern solves problems like:[3]

  • How can objects be created so that which objects to create can be specified at run-time?
  • How can dynamically loaded classes be instantiated?

Creating objects directly within the class that requires (uses) the objects is inflexible because it commits the class to particular objects at compile-time and makes it impossible to specify which objects to create at run-time.

The prototype design pattern describes how to solve such problems:

  • Define a Prototype object that returns a copy of itself.
  • Create new objects by copying a Prototype object.

This enables configuration of a class with different Prototype objects, which are copied to create new objects, and even more, Prototype objects can be added and removed at run-time.
See also the UML class and sequence diagram below.

Structure

UML class and sequence diagram

 
A sample UML class and sequence diagram for the Prototype design pattern.

In the above UML class diagram, the Client class refers to the Prototype interface for cloning a Product. The Product1 class implements the Prototype interface by creating a copy of itself.
The UML sequence diagram shows the run-time interactions: The Client object calls clone() on a prototype:Product1 object, which creates and returns a copy of itself (a product:Product1 object).

UML class diagram

 
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.[2]: 126  Abstract factory, builder, and prototype can use singleton in their implementations.[2]: 81, 134  Abstract factory classes are often implemented with factory methods (creation through inheritance), but they can be implemented using prototype (creation through delegation).[2]: 95 

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.[2]: 136 

Prototype does not require subclassing, but it does require an "initialize" operation. Factory method requires subclassing, but does not require initialization.[2]: 116 

Designs that make heavy use of the composite and decorator patterns often can benefit from Prototype as well.[2]: 126 

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.

Code samples

This C++11 implementation is based on the pre C++98 implementation in the book.

#include <iostream>

enum Direction {North, South, East, West};

class MapSite { // Prototype
public:
  virtual MapSite* clone() const = 0; // declares an interface for cloning itself.
  virtual ~MapSite() = default;
};

class Room : public MapSite { // ConcretePrototype
public:
  Room() :roomNumber(0) {}
  Room(int n) :roomNumber(n) {}
  virtual Room* clone() const { // implements an operation for cloning itself.
    std::cout << "Room::clone\n";
    return new Room(*this);
  }
  void setSide(Direction, MapSite*) {}
  Room& operator=(const Room&) = delete;
private:
  int roomNumber;
};

class Wall : public MapSite { // ConcretePrototype
public:
  Wall() {}
  virtual Wall* clone() const { 
    std::cout << "Wall::clone\n";
    return new Wall(*this);
  }
};

class Door : public MapSite { // ConcretePrototype
public:
  Door() :room1(nullptr), room2(nullptr) {}
  Door(const Door& other) :room1(other.room1), room2(other.room2) {}
  Door(Room* r1, Room* r2) :room1(r1), room2(r2) {}
  virtual Door* clone() const {
    std::cout << "Door::clone\n";
    return new Door(*this);
  }
  virtual void initialize(Room* r1, Room* r2) {
    room1 = r1;
    room2 = r2;
  }
  Door& operator=(const Door&) = delete;
private:
  Room* room1;
  Room* room2;
};

class Maze {
public:
  virtual Maze* clone() const {
    std::cout << "Maze::clone\n";
    return new Maze(*this);
  }
  void addRoom(Room*) {}
  virtual ~Maze() = default;
};

class MazeFactory {
public:
  MazeFactory() = default;
  virtual ~MazeFactory() = default;

  virtual Maze* makeMaze() const {
    return new Maze;
  }
  virtual Wall* makeWall() const {
    return new Wall;
  }
  virtual Room* makeRoom(int n) const {
    return new Room(n);
  }
  virtual Door* makeDoor(Room* r1, Room* r2) const {
    return new Door(r1, r2);
  }
};

class MazePrototypeFactory : public MazeFactory { // Client
public:
  MazePrototypeFactory(Maze* m, Wall* w, Room* r, Door* d)
    :prototypeMaze(m), prototypeRoom(r),
    prototypeWall(w), prototypeDoor(d) {}
  virtual Maze* makeMaze() const {
    // creates a new object by asking a prototype to clone itself.
    return prototypeMaze->clone();
  }
  virtual Room* makeRoom(int) const { 
    return prototypeRoom->clone();
  }
  virtual Wall* makeWall() const {
    return prototypeWall->clone();
  }
  virtual Door* makeDoor(Room* r1, Room* r2) const {
    Door* door = prototypeDoor->clone();
    door->initialize(r1, r2);
    return door;
  }
  MazePrototypeFactory(const MazePrototypeFactory&) = delete;
  MazePrototypeFactory& operator=(const MazePrototypeFactory&) = delete;
private:
  Maze* prototypeMaze;
  Room* prototypeRoom;
  Wall* prototypeWall;
  Door* prototypeDoor;
};

class MazeGame {
public:
  Maze* createMaze(MazePrototypeFactory& m) {
    Maze* aMaze = m.makeMaze();
    Room* r1 = m.makeRoom(1);
    Room* r2 = m.makeRoom(2);
    Door* theDoor = m.makeDoor(r1, r2);
    aMaze->addRoom(r1);
    aMaze->addRoom(r2);
    r1->setSide(North, m.makeWall());
    r1->setSide(East, theDoor);
    r1->setSide(South, m.makeWall());
    r1->setSide(West, m.makeWall());
    r2->setSide(North, m.makeWall());
    r2->setSide(East, m.makeWall());
    r2->setSide(South, m.makeWall());
    r2->setSide(West, theDoor);
    return aMaze;  
  }
};

int main() {
  MazeGame game;
  MazePrototypeFactory simpleMazeFactory(new Maze, new Wall, new Room, new Door);

  Maze* maze = game.createMaze(simpleMazeFactory);
}

The program output is:

Maze::clone
Room::clone
Room::clone
Door::clone
Wall::clone
Wall::clone
Wall::clone
Wall::clone
Wall::clone
Wall::clone

C# example

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

C++ example

Discussion of the design pattern along with a complete illustrative example implementation using polymorphic class design are provided in the C++ Annotations.

Java example

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();
    }
}

PHP example

// 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

Python example

Python version 3.9+

import copy

class Prototype:
    def clone(self):
        return copy.deepcopy(self)

if __name__ == "__main__":
    prototype = Prototype()
    prototype_copy = prototype.clone()
    print(prototype_copy)

Output:

<__main__.Prototype object at 0x7fae8f4e2940>

See also

References

  1. ^ Duell, Michael (July 1997). "Non-Software Examples of Design Patterns". Object Magazine. 7 (5): 54. ISSN 1055-3614.
  2. ^ a b c d e f g Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software. Addison-Wesley. ISBN 0-201-63361-2.
  3. ^ "The Prototype design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-17.