![]() | This article has multiple issues. Please help improve it or discuss these issues on the talk page . (Learn how and when to remove these messages)
|
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 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]
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]
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 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.
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).
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.
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 C++ Annotations.
importstd;enumclassDirection{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::println("Room::setSide {} ms",d);}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::println("Maze::addRoom {}",r);}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(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);returnaMaze;}};intmain(){MazeGamegame;MazePrototypeFactorysimpleMazeFactory(newMaze,newWall,newRoom,newDoor);game.createMaze(simpleMazeFactory);}
The program output is:
Maze::addRoom0x1160f50Maze::addRoom0x1160f70Room::setSide00x11613c0Room::setSide20x1160f90Room::setSide10x11613e0Room::setSide30x1161400Room::setSide00x1161420Room::setSide20x1161440Room::setSide10x1161460Room::setSide30x1160f90
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 without specifying their concrete classes. According to this pattern, a client software component creates a concrete implementation of the abstract factory and then uses the generic interface of the factory to create the concrete objects that are part of the family. The client does not know which concrete objects it receives from each of these internal factories, as it uses only the generic interfaces of their products. This pattern separates the details of implementation of a set of objects from their general usage and relies on object composition, as object creation is implemented in methods exposed in the factory interface.
Prototype-based programming is a style of object-oriented programming in which behavior reuse is performed via a process of reusing existing objects that serve as prototypes. This model can also be known as prototypal, prototype-oriented,classless, or instance-based programming.
The bridge pattern is a design pattern used in software engineering that is meant to "decouple an abstraction from its implementation so that the two can vary independently", introduced by the Gang of Four. The bridge uses encapsulation, aggregation, and can use inheritance to separate responsibilities into different classes.
In object-oriented programming, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. It is one of the well-known "Gang of Four" design patterns, which describe how to solve recurring problems in object-oriented software. The pattern is useful when exactly one object is needed to coordinate actions across a system.
In computer programming, the flyweight software design pattern refers to an object that minimizes memory usage by sharing some of its data with other similar objects. The flyweight pattern is one of twenty-three well-known GoF design patterns. These patterns promote flexible object-oriented software design, which is easier to implement, change, test, and reuse.
In object-oriented programming, the factory method pattern is a design pattern that uses factory methods to deal with the problem of creating objects without having to specify their exact classes. Rather than by calling a constructor, this is accomplished by invoking a factory method to create an object. Factory methods can be specified in an interface and implemented by subclasses or implemented in a base class and optionally overridden by subclasses. It is one of the 23 classic design patterns described in the book Design Patterns and is subcategorized as a creational pattern.
In software engineering, the composite pattern is a partitioning design pattern. The composite pattern describes a group of objects that are treated the same way as a single instance of the same type of object. The intent of a composite is to "compose" objects into tree structures to represent part-whole hierarchies. Implementing the composite pattern lets clients treat individual objects and compositions uniformly.
In object-oriented programming, the decorator pattern is a design pattern that allows behavior to be added to an individual object, dynamically, without affecting the behavior of other instances of the same class. The decorator pattern is often useful for adhering to the Single Responsibility Principle, as it allows functionality to be divided between classes with unique areas of concern as well as to the Open-Closed Principle, by allowing the functionality of a class to be extended without being modified. Decorator use can be more efficient than subclassing, because an object's behavior can be augmented without defining an entirely new object.
In computer programming, the interpreter pattern is a design pattern that specifies how to evaluate sentences in a language. The basic idea is to have a class for each symbol in a specialized computer language. The syntax tree of a sentence in the language is an instance of the composite pattern and is used to evaluate (interpret) the sentence for a client. See also Composite pattern.
In software design and engineering, the observer pattern is a software design pattern in which an object, named the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
A method in object-oriented programming (OOP) is a procedure associated with an object, and generally also a message. An object consists of state data and behavior; these compose an interface, which specifies how the object may be used. A method is a behavior of an object parametrized by a user.
In object-oriented programming such as is often used in C++ and Object Pascal, a virtual function or virtual method is an inheritable and overridable function or method that is dispatched dynamically. Virtual functions are an important part of (runtime) polymorphism in object-oriented programming (OOP). They allow for the execution of target functions that were not precisely identified at compile time.
In software engineering, creational design patterns are design patterns that deal with object creation mechanisms, trying to create objects in a manner suitable to the situation. The basic form of object creation could result in design problems or in added complexity to the design due to inflexibility in the creation procedures. Creational design patterns solve this problem by somehow controlling this object creation.
In object-oriented programming, a factory is an object for creating other objects; formally, it is a function or method that returns objects of a varying prototype or class from some method call, which is assumed to be new. More broadly, a subroutine that returns a new object may be referred to as a factory, as in factory method or factory function. The factory pattern is the basis for a number of related software design patterns.
In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object or class, retaining similar implementation. Also defined as deriving new classes from existing ones such as super class or base class and then forming them into a hierarchy of classes. In most class-based object-oriented languages like C++, an object created through inheritance, a "child object", acquires all the properties and behaviors of the "parent object", with the exception of: constructors, destructors, overloaded operators and friend functions of the base class. Inheritance allows programmers to create classes that are built upon existing classes, to specify a new implementation while maintaining the same behaviors, to reuse code and to independently extend original software via public classes and interfaces. The relationships of objects or classes through inheritance give rise to a directed acyclic graph.
Automata-based programming is a programming paradigm in which the program or part of it is thought of as a model of a finite-state machine (FSM) or any other formal automaton. Sometimes a potentially infinite set of possible states is introduced, and such a set can have a complicated structure, not just an enumeration.
The curiously recurring template pattern (CRTP) is an idiom, originally in C++, in which a class X
derives from a class template instantiation using X
itself as a template argument. More generally it is known as F-bound polymorphism, and it is a form of F-bounded quantification.
In software engineering, a fluent interface is an object-oriented API whose design relies extensively on method chaining. Its goal is to increase code legibility by creating a domain-specific language (DSL). The term was coined in 2005 by Eric Evans and Martin Fowler.
In object-oriented computer programming, a null object is an object with no referenced value or with defined neutral (null) behavior. The null object design pattern, which describes the uses of such objects and their behavior, was first published as "Void Value" and later in the Pattern Languages of Program Design book series as "Null Object".
In object-oriented design, the chain-of-responsibility pattern is a behavioral design pattern consisting of a source of command objects and a series of processing objects. Each processing object contains logic that defines the types of command objects that it can handle; the rest are passed to the next processing object in the chain. A mechanism also exists for adding new processing objects to the end of this chain.