The prototype pattern is a creational design pattern in software development. It is used when the types of objects to create is determined by a prototypicalinstance, 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 virtualclone() method. Any class that needs a "polymorphicconstructor" 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 the specific type of object can be determined at runtime?
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
In the above UMLclass 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 UMLsequence 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
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
A general guideline in programming suggests using the clone() method when creating a duplicate object during runtime to ensure it accurately reflects the original object. This process, known as object cloning, produces a new object with identical attributes to the one being cloned. Alternatively, instantiating a class using the new keyword generates an object with default attribute values.
For instance, in the context of designing a system for managing bank account transactions, it may be necessary to duplicate the object containing account information to conduct transactions while preserving the original data. In such scenarios, employing the clone() method is preferable over using new to instantiate a new object.
Example
C++11 Example
This C++11 implementation is based on the pre C++98 implementation in the book. Discussion of the design pattern along with a complete illustrative example implementation using polymorphic class design are provided in the C++ Annotations.
#include<iostream>enumDirection{North,South,East,West};classMapSite{public:virtualvoidenter()=0;virtualMapSite*clone()const=0;virtual~MapSite()=default;};classRoom:publicMapSite{public:Room():roomNumber(0){}Room(intn):roomNumber(n){}voidsetSide(Directiond,MapSite*ms){std::cout<<"Room::setSide "<<d<<' '<<ms<<'\n';}virtualvoidenter(){}virtualRoom*clone()const{// implements an operation for cloning itself.returnnewRoom(*this);}Room&operator=(constRoom&)=delete;private:introomNumber;};classWall:publicMapSite{public:Wall(){}virtualvoidenter(){}virtualWall*clone()const{returnnewWall(*this);}};classDoor:publicMapSite{public:Door(Room*r1=nullptr,Room*r2=nullptr):room1(r1),room2(r2){}Door(constDoor&other):room1(other.room1),room2(other.room2){}virtualvoidenter(){}virtualDoor*clone()const{returnnewDoor(*this);}virtualvoidinitialize(Room*r1,Room*r2){room1=r1;room2=r2;}Door&operator=(constDoor&)=delete;private:Room*room1;Room*room2;};classMaze{public:voidaddRoom(Room*r){std::cout<<"Maze::addRoom "<<r<<'\n';}Room*roomNo(int)const{returnnullptr;}virtualMaze*clone()const{returnnewMaze(*this);}virtual~Maze()=default;};classMazeFactory{public:MazeFactory()=default;virtual~MazeFactory()=default;virtualMaze*makeMaze()const{returnnewMaze;}virtualWall*makeWall()const{returnnewWall;}virtualRoom*makeRoom(intn)const{returnnewRoom(n);}virtualDoor*makeDoor(Room*r1,Room*r2)const{returnnewDoor(r1,r2);}};classMazePrototypeFactory:publicMazeFactory{public:MazePrototypeFactory(Maze*m,Wall*w,Room*r,Door*d):prototypeMaze(m),prototypeRoom(r),prototypeWall(w),prototypeDoor(d){}virtualMaze*makeMaze()const{// creates a new object by asking a prototype to clone itself.returnprototypeMaze->clone();}virtualRoom*makeRoom(int)const{returnprototypeRoom->clone();}virtualWall*makeWall()const{returnprototypeWall->clone();}virtualDoor*makeDoor(Room*r1,Room*r2)const{Door*door=prototypeDoor->clone();door->initialize(r1,r2);returndoor;}MazePrototypeFactory(constMazePrototypeFactory&)=delete;MazePrototypeFactory&operator=(constMazePrototypeFactory&)=delete;private:Maze*prototypeMaze;Room*prototypeRoom;Wall*prototypeWall;Door*prototypeDoor;};// If createMaze is parameterized by various prototypical room, door, and wall objects, which it then copies and adds to the maze, then you can change the maze's composition by replacing these prototypical objects with different ones. This is an example of the Prototype (133) pattern.classMazeGame{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);returnaMaze;}};intmain(){MazeGamegame;MazePrototypeFactorysimpleMazeFactory(newMaze,newWall,newRoom,newDoor);game.createMaze(simpleMazeFactory);}