Prototype pattern

Last updated

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.

Contents

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]

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]

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:

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

A sample UML class and sequence diagram for the Prototype design pattern. W3sDesign Prototype Design Pattern UML.jpg
A sample UML class and sequence diagram for the Prototype design pattern.

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).

UML class diagram

UML class diagram describing the prototype design pattern Prototype UML.svg
UML class diagram describing the prototype design pattern

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

This C++11 implementation is based on the pre C++98 implementation in the book.

#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);}

The program output is:

Maze::addRoom0x1160f50Maze::addRoom0x1160f70Room::setSide00x11613c0Room::setSide20x1160f90Room::setSide10x11613e0Room::setSide30x1161400Room::setSide00x1161420Room::setSide20x1161440Room::setSide10x1161460Room::setSide30x1160f90

C++ example

Discussion of the design pattern along with a complete illustrative example implementation using polymorphic class design are provided in the C++ Annotations.

See also

Related Research Articles

<span class="mw-page-title-main">Abstract factory pattern</span> Software design pattern

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 behaviour 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.

<span class="mw-page-title-main">Singleton pattern</span> Design pattern in object-oriented software development

In software engineering, the singleton pattern is a software design pattern that restricts the instantiation of a class to a singular instance. One of the well-known "Gang of Four" design patterns, which describes 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.

<span class="mw-page-title-main">Flyweight pattern</span> Software design pattern for objects

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 creational pattern that uses factory methods to deal with the problem of creating objects without having to specify the exact class of the object that will be created. This is done by creating objects by calling a factory method—either specified in an interface and implemented by child classes, or implemented in a base class and optionally overridden by derived classes—rather than by calling a constructor.

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 the C++ programming language, a reference is a simple reference datatype that is less powerful but safer than the pointer type inherited from C. The name C++ reference may cause confusion, as in computer science a reference is a general concept datatype, with pointers and C++ references being specific reference datatype implementations. The definition of a reference in C++ is such that it does not need to exist. It can be implemented as a new name for an existing object.

<span class="mw-page-title-main">Method overriding</span> Language feature in object-oriented programming

Method overriding, in object-oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes. In addition to providing data-driven algorithm-determined parameters across virtual network interfaces, it also allows for a specific type of polymorphism (subtyping). The implementation in the subclass overrides (replaces) the implementation in the superclass by providing a method that has same name, same parameters or signature, and same return type as the method in the parent class. The version of a method that is executed will be determined by the object that is used to invoke it. If an object of a parent class is used to invoke the method, then the version in the parent class will be executed, but if an object of the subclass is used to invoke the method, then the version in the child class will be executed. This helps in preventing problems associated with differential relay analytics which would otherwise rely on a framework in which method overriding might be obviated. Some languages allow a programmer to prevent a method from being overridden.

<span class="mw-page-title-main">Factory (object-oriented programming)</span> Object that creates other objects

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.

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".

References

  1. Duell, Michael (July 1997). "Non-Software Examples of Design Patterns". Object Magazine. 7 (5): 54. ISSN   1055-3614.
  2. 1 2 3 4 5 6 7 Gamma, Erich; Helm, Richard; Johnson, Ralph; Vlissides, John (1994). Design Patterns: Elements of Reusable Object-Oriented Software . Addison-Wesley. ISBN   0-201-63361-2.
  3. "The Prototype design pattern - Problem, Solution, and Applicability". w3sDesign.com. Retrieved 2017-08-17.