Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
Prototype pattern
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
{{Short description|Creational design pattern in software development}} {{other uses|Software prototyping}} {{distinguish|Prototype-based programming|Function prototype}} {{multiple issues| {{Refimprove|date=November 2014}} {{tone|date=June 2019}} }} The '''prototype pattern''' is a creational [[design pattern (computer science)|design pattern]] in [[software development]]. It is used when the types of [[object (computer science)|object]]s to create is determined by a [[prototype|prototypical]] [[instance (computer science)|instance]], which is cloned to produce new objects. This pattern is used to avoid [[subclass (computer science)|subclass]]es 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 (C++)|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 [[virtual method#Abstract classes and pure virtual functions|pure virtual]] ''clone()'' method. Any class that needs a "[[polymorphism (computer science)|polymorphic]] [[constructor (computer science)|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 [[mitosis|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.{{refn|1= {{cite journal |last1=Duell |first1=Michael |title=Non-Software Examples of Design Patterns |journal=Object Magazine |volume=7 |issue=5 |date=July 1997 |pages=54 |issn=1055-3614}} }} ==Overview== The prototype design pattern is one of the 23 [[Design Patterns|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.{{r|GoF|p=117}} The prototype design pattern solves problems like:{{refn|1={{cite web|title=The Prototype design pattern - Problem, Solution, and Applicability|url=http://w3sdesign.com/?gr=c04&ugr=proble|website=w3sDesign.com|access-date=2017-08-17}} }} * 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 <code>Prototype</code> object that returns a copy of itself. * Create new objects by copying a <code>Prototype</code> object. This enables configuration of a class with different <code>Prototype</code> objects, which are copied to create new objects, and even more, <code>Prototype</code> objects can be added and removed at run-time.<br> See also the UML class and sequence diagram below. ==Structure== === UML class and sequence diagram === [[File:w3sDesign Prototype Design Pattern UML.jpg|frame|none|A sample UML class and sequence diagram for the Prototype design pattern.]] In the above [[Unified Modeling Language|UML]] [[class diagram]], the <code>Client</code> class refers to the <code>Prototype</code> interface for cloning a <code>Product</code>. The <code>Product1</code> class implements the <code>Prototype</code> interface by creating a copy of itself. <br> The [[Unified Modeling Language|UML]] [[sequence diagram]] shows the run-time interactions: The <code>Client</code> object calls <code>clone()</code> on a <code>prototype:Product1</code> object, which creates and returns a copy of itself (a <code>product:Product1</code> object). === UML class diagram === [[File:Prototype UML.svg|thumb|center|600px|[[Unified Modeling Language|UML]] class diagram describing the prototype design pattern]] == Rules of thumb == Sometimes [[creational pattern]]s overlap—there are cases when either prototype or [[abstract factory pattern|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.{{r|GoF|p=126}} Abstract factory, [[builder pattern|builder]], and prototype can use [[singleton pattern|singleton]] in their implementations.{{r|GoF|pp=81,134}} Abstract factory classes are often implemented with factory methods (creation through [[inheritance (object-oriented programming)|inheritance]]), but they can be implemented using prototype (creation through [[delegation (programming)|delegation]]).{{r|GoF|p=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.{{r|GoF|p=136}} Prototype does not require subclassing, but it does require an "initialize" operation. Factory method requires subclassing, but does not require initialization.{{r|GoF|p=116}} Designs that make heavy use of the [[composite pattern|composite]] and [[decorator pattern|decorator]] patterns often can benefit from Prototype as well.{{r|GoF|p=126}} A general guideline in programming suggests using the <code>clone()</code> 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 <code>new</code> 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 <code>clone()</code> method is preferable over using <code>new</code> to instantiate a new object. == Example == === C++11 Example === This [[C++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 the [https://fbb-git.gitlab.io/cppannotations/cppannotations/html/cplusplus14.html#l318 C++ Annotations]. <syntaxhighlight lang="c++"> import std; enum class Direction {North, South, East, West}; class MapSite { public: virtual void enter() = 0; virtual MapSite* clone() const = 0; virtual ~MapSite() = default; }; class Room : public MapSite { public: Room(): roomNumber(0) {} Room(int n): roomNumber(n) {} void setSide(Direction d, MapSite* ms) { std::println("Room::setSide {} ms", d); } virtual void enter() {} virtual Room* clone() const { // implements an operation for cloning itself. return new Room(*this); } Room& operator=(const Room&) = delete; private: int roomNumber; }; class Wall: public MapSite { public: Wall() {} virtual void enter() {} virtual Wall* clone() const { return new Wall(*this); } }; class Door: public MapSite { public: Door(Room* r1 = nullptr, Room* r2 = nullptr) :room1(r1), room2(r2) {} Door(const Door& other) :room1(other.room1), room2(other.room2) {} virtual void enter() {} virtual Door* clone() const { 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: void addRoom(Room* r) { std::println("Maze::addRoom {}", r); } Room* roomNo(int) const { return nullptr; } virtual Maze* clone() const { return new Maze(*this); } 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 { 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; }; // 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. 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(Direction::North, m.makeWall()); r1->setSide(Direction::East, theDoor); r1->setSide(Direction::South, m.makeWall()); r1->setSide(Direction::West, m.makeWall()); r2->setSide(Direction::North, m.makeWall()); r2->setSide(Direction::East, m.makeWall()); r2->setSide(Direction::South, m.makeWall()); r2->setSide(Direction::West, theDoor); return aMaze; } }; int main() { MazeGame game; MazePrototypeFactory simpleMazeFactory(new Maze, new Wall, new Room, new Door); game.createMaze(simpleMazeFactory); } </syntaxhighlight> The program output is: <syntaxhighlight lang="c++"> Maze::addRoom 0x1160f50 Maze::addRoom 0x1160f70 Room::setSide 0 0x11613c0 Room::setSide 2 0x1160f90 Room::setSide 1 0x11613e0 Room::setSide 3 0x1161400 Room::setSide 0 0x1161420 Room::setSide 2 0x1161440 Room::setSide 1 0x1161460 Room::setSide 3 0x1160f90 </syntaxhighlight> == See also == {{Wikibooks|Computer Science Design Patterns|Prototype|Prototype implementations in various languages}} * [[Function prototype]] == References == {{reflist |refs= {{refn |name=GoF |1= {{cite book |last1=Gamma |first1=Erich |author-link1=Erich Gamma |last2=Helm |first2=Richard |last3=Johnson |first3=Ralph |author-link3=Ralph Johnson (computer scientist) |last4=Vlissides |first4=John |author-link4=John Vlissides |title=Design Patterns: Elements of Reusable Object-Oriented Software |publisher=Addison-Wesley |year=1994 |isbn=0-201-63361-2 |url=https://archive.org/details/designpatternsel00gamm |url-access=registration }} }} }} {{Design Patterns Patterns}} <!--Categories--> [[Category:Software design patterns]] [[Category:Articles with example Java code]]
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)
Pages transcluded onto the current version of this page
(
help
)
:
Template:Design Patterns Patterns
(
edit
)
Template:Distinguish
(
edit
)
Template:Multiple issues
(
edit
)
Template:Other uses
(
edit
)
Template:R
(
edit
)
Template:Reflist
(
edit
)
Template:Refn
(
edit
)
Template:Short description
(
edit
)
Template:Sister project
(
edit
)
Template:Wikibooks
(
edit
)