Prototype pattern
   HOME

TheInfoList



OR:

The prototype pattern is a creational
design pattern A design pattern is the re-usable form of a solution to a design problem. The idea was introduced by the architect Christopher Alexander and has been adapted for various other disciplines, particularly software engineering. The " Gang of Four" ...
in
software development Software development is the process of designing and Implementation, implementing a software solution to Computer user satisfaction, satisfy a User (computing), user. The process is more encompassing than Computer programming, programming, wri ...
. It is used when the types of
object Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not exist at any particular time or place ** Physical object, an identifiable collection of matter * Goal, an a ...
s 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 In object-oriented programming, the factory method pattern is a software design pattern, design pattern that uses factory methods to deal with the problem of object creation, creating objects without having to specify their exact class (computer pr ...
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 A parameter (), generally, is any characteristic that can help in defining or classifying a particular system (meaning an event, project, object, situation, etc.). That is, a parameter is an element of a system that is useful, or critical, when ...
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.


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. The prototype design pattern solves problems like: * 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 UML
class diagram In software engineering, a class diagram in the Unified Modeling Language (UML) is a type of static structure diagram that describes the structure of a system by showing the system's classes, their attributes, operations (or methods), and the re ...
, 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 In software engineering, a sequence diagram shows process interactions arranged in time sequence. This diagram depicts the processes and objects involved and the sequence of messages exchanged as needed to carry out the functionality. Sequence ...
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 pattern In software engineering, creational design patterns are design patterns that deal with object creation Object may refer to: General meanings * Object (philosophy), a thing, being, or concept ** Object (abstract), an object which does not ex ...
s overlap—there are cases when either prototype or
abstract factory The abstract factory pattern in software engineering is a design pattern that provides a way to create families of related objects without imposing their concrete classes, by encapsulating a group of individual factories that have a common theme w ...
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. Abstract factory, builder, and prototype can use singleton in their implementations. Abstract factory classes are often implemented with factory methods (creation through
inheritance Inheritance is the practice of receiving private property, titles, debts, entitlements, privileges, rights, and obligations upon the death of an individual. The rules of inheritance differ among societies and have changed over time. Offi ...
), but they can be implemented using prototype (creation through
delegation Delegation is the process of distributing and entrusting work to another person.Schermerhorn, J., Davidson, P., Poole, D., Woods, P., Simon, A., & McBarron, E. (2017). ''Management'' (6th ed., pp. 282–286). Brisbane: John Wiley & Sons Australia. ...
). 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. Prototype does not require subclassing, but it does require an "initialize" operation. Factory method requires subclassing, but does not require initialization. Designs that make heavy use of the composite and decorator patterns often can benefit from Prototype as well. 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++23 C++23, formally ISO/IEC 14882:2024, is the current open standard for the C++ programming language that follows C++20. The final draft of this version is N4950. In February 2020, at the final meeting for C++20 in Prague, an overall plan for C++ ...
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 th
C++ Annotations
import std; enum class Direction ; class MapSite ; class Room : public MapSite ; class Wall: public MapSite ; class Door: public MapSite ; class Maze ; class MazeFactory ; class MazePrototypeFactory: public MazeFactory ; // 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 ; int main() The program output is: 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


See also

*
Function prototype In computer programming, a function prototype is a declaration of a function that specifies the function's name and type signature (arity, data types of parameters, and return type), but omits the function body. While a function definition ...


References

{{Design Patterns Patterns Software design patterns Articles with example Java code