This article has multiple issues. Please helpimprove it or discuss these issues on thetalk page.(Learn how and when to remove these messages) (Learn how and when to remove this message)
|
Theprototype pattern is a creationaldesign pattern insoftware development. It is used when the types ofobjects to create is determined by aprototypicalinstance, which is cloned to produce new objects. This pattern is used to avoidsubclasses of an object creator in the client application, like thefactory 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 abstractbase class that specifies apure virtualclone() method. Any class that needs a "polymorphicconstructor" capability derives itself from the abstract base class, and implements theclone() operation.
The client, instead of writing code that invokes the "new" operator on a hard-coded class name, calls theclone() method on the prototype, calls afactory method with aparameter designating the particular concretederived class desired, or invokes theclone() method through some mechanism provided by another design pattern.
Themitotic 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]
The prototype design pattern is one of the 23Gang 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]
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:
Prototype object that returns a copy of itself.Prototype object.This enables configuration of a class with differentPrototype 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.

In the aboveUMLclass diagram, theClient class refers to thePrototype interface for cloning aProduct.TheProduct1 class implements thePrototype interface by creating a copy of itself.
TheUMLsequence diagram shows the run-time interactions: TheClient object callsclone() on aprototype:Product1 object, which creates and returns a copy of itself (aproduct:Product1 object).

Sometimescreational patterns overlap—there are cases when either prototype orabstract 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 usesingleton in their implementations.[2]: 81, 134 Abstract factory classes are often implemented with factory methods (creation throughinheritance), but they can be implemented using prototype (creation throughdelegation).[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 thecomposite anddecorator patterns often can benefit from Prototype as well.[2]: 126
A general guideline in programming suggests using theclone() 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 thenew 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 theclone() method is preferable over usingnew to instantiate a new object.
ThisC++23 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 theC++ Annotations.
importstd;usingstd::array;usingstd::shared_ptr;usingstd::unique_ptr;usingstd::vector;enumclassDirection:char{NORTH,SOUTH,EAST,WEST};classMapSite{public:virtualvoidenter()=0;virtualunique_ptr<MapSite>clone()const=0;virtual~MapSite()=default;};classRoom:publicMapSite{private:introomNumber;shared_ptr<array<shared_ptr<MapSite>,4>>sides;public:explicitRoom(intn=0):roomNumber{n},sides{std::make_shared<array<shared_ptr<MapSite>,4>>()}{}~Room()=default;Room&setSide(Directiond,shared_ptr<MapSite>ms){(*sides)[static_cast<size_t>(d)]=std::move(ms);std::println("Room::setSide {} ms",d);return*this;}virtualvoidenter()override{}virtualunique_ptr<MapSite>clone()constoverride{returnstd::make_unique<Room>(*this);}Room(constRoom&)=delete;Room&operator=(constRoom&)=delete;};classWall:publicMapSite{public:Wall():MapSite(){}~Wall()=default;virtualvoidenter()override{}[[nodiscard]]virtualunique_ptr<MapSite>clone()constoverride{returnstd::make_unique<Wall>(*this);}};classDoor:publicMapSite{private:shared_ptr<Room>room1;shared_ptr<Room>room2;public:explicitDoor(shared_ptr<Room>r1=nullptr,shared_ptr<Room>r2=nullptr):MapSite(),room1{std::move(r1)},room2{std::move(r2)}{}~Door()=default;virtualvoidenter()override{}[[nodiscard]]virtualunique_ptr<MapSite>clone()constoverride{returnstd::make_unique<Door>(*this);}voidinitialize(shared_ptr<Room>r1,shared_ptr<Room>r2){room1=std::move(r1);room2=std::move(r2);}Door(constDoor&)=delete;Door&operator=(constDoor&)=delete;};classMaze{private:vector<shared_ptr<Room>>rooms;public:Maze()=default;~Maze()=default;Maze&addRoom(shared_ptr<Room>r){std::println("Maze::addRoom {}",reinterpret_cast<void*>(r.get()));rooms.push_back(std::move(r));return*this;}[[nodiscard]]shared_ptr<Room>roomNo(intn)const{for(constRoom&r:rooms){// actual lookup logic here...}returnnullptr;}[[nodiscard]]virtualunique_ptr<Maze>clone()const{returnstd::make_unique<Maze>(*this);}};classMazeFactory{public:MazeFactory()=default;virtual~MazeFactory()=default;[[nodiscard]]virtualunique_ptr<Maze>makeMaze()const{returnstd::make_unique<Maze>();}[[nodiscard]]virtualshared_ptr<Wall>makeWall()const{returnstd::make_shared<Wall>();}[[nodiscard]]virtualshared_ptr<Room>makeRoom(intn)const{returnstd::make_shared<Room>(n);}[[nodiscard]]virtualshared_ptr<Door>makeDoor(shared_ptr<Room>r1,shared_ptr<Room>r2)const{returnstd::make_shared<Door>(std::move(r1),std::move(r2));}};classMazePrototypeFactory:publicMazeFactory{private:unique_ptr<Maze>prototypeMaze;shared_ptr<Room>prototypeRoom;shared_ptr<Wall>prototypeWall;shared_ptr<Door>prototypeDoor;public:MazePrototypeFactory(unique_ptr<Maze>m,shared_ptr<Wall>w,shared_ptr<Room>r,shared_ptr<Door>d):MazeFactory(),prototypeMaze{std::move(m)},prototypeRoom{std::move(r)},prototypeWall{std::move(w)},prototypeDoor{std::move(d)}{}~MazePrototypeFactory()=default;virtualunique_ptr<Maze>makeMaze()constoverride{returnprototypeMaze->clone();}[[nodiscard]]virtualshared_ptr<Room>makeRoom(intn)constoverride{returnprototypeRoom->clone();}[[nodiscard]]virtualshared_ptr<Wall>makeWall()constoverride{returnprototypeWall->clone();}[[nodiscard]]virtualshared_ptr<Door>makeDoor(shared_ptr<Room>r1,shared_ptr<Room>r2)constoverride{shared_ptr<Door>door=prototypeDoor->clone();door->initialize(std::move(r1),std::move(r2));returndoor;}MazePrototypeFactory(constMazePrototypeFactory&)=delete;MazePrototypeFactory&operator=(constMazePrototypeFactory&)=delete;};classMazeGame{public:MazeGame()=default;~MazeGame()=default;[[nodiscard]]unique_ptr<Maze>createMaze(MazePrototypeFactory&factory){unique_ptr<Maze>maze=factory.makeMaze();shared_ptr<Room>r1=factory.makeRoom(1);shared_ptr<Room>r2=factory.makeRoom(2);shared_ptr<Door>door=factory.makeDoor(r1,r2);maze->addRoom(std::move(r1)).addRoom(std::move(r2));r1->setSide(Direction::NORTH,factory.makeWall()).setSide(Direction::EAST,door).setSide(Direction::SOUTH,factory.makeWall()).setSide(Direction::WEST,factory.makeWall());r2->setSide(Direction::NORTH,factory.makeWall()).setSide(Direction::EAST,factory.makeWall()).setSide(Direction::SOUTH,factory.makeWall()).setSide(Direction::WEST,door);returnmaze;}};intmain(intargc,char*argv[]){MazeGamegame;MazePrototypeFactorysimpleMazeFactory(std::make_unique<Maze>(),std::make_shared<Wall>(),std::make_shared<Room>(0),std::make_shared<Door>());unique_ptr<Maze>maze=game.createMaze(simpleMazeFactory);}
The program output is:
Maze::addRoom0x1160f50Maze::addRoom0x1160f70Room::setSide00x11613c0Room::setSide20x1160f90Room::setSide10x11613e0Room::setSide30x1161400Room::setSide00x1161420Room::setSide20x1161440Room::setSide10x1161460Room::setSide30x1160f90