Prototype pattern
   HOME

TheInfoList



OR:

The prototype pattern is a creational design pattern in
software development Software development is the process of conceiving, specifying, designing, programming, documenting, testing, and bug fixing involved in creating and maintaining applications, frameworks, or other software components. Software development invo ...
. It is used when the type 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 ...
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 does and to avoid the inherent cost of creating a new object in the standard way (e.g., using the '
new New is an adjective referring to something recently made, discovered, or created. New or NEW may refer to: Music * New, singer of K-pop group The Boyz Albums and EPs * ''New'' (album), by Paul McCartney, 2013 * ''New'' (EP), by Regurgitator, ...
' keyword) when it is prohibitively expensive for a given application. To implement the pattern, the client declares an abstract
base class In object-oriented programming, inheritance is the mechanism of basing an object or class upon another object ( prototype-based inheritance) or class ( class-based inheritance), retaining similar implementation. Also defined as deriving new classe ...
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 In class-based 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 c ...
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 In cell biology, mitosis () is a part of the cell cycle in which replicated chromosomes are separated into two new nuclei. Cell division by mitosis gives rise to genetically identical cells in which the total number of chromosomes is maintai ...
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 twenty-three well-known GoF 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 which objects to create can be specified at run-time? * 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 rela ...
, 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


Rules of thumb

Sometimes creational patterns overlap — there are cases when either prototype or
abstract factory The abstract factory pattern provides a way to encapsulate a group of individual factories that have a common theme without specifying their concrete classes. In normal usage, the client software creates a concrete implementation of the abstract fa ...
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. Of ...
), but they can be implemented using prototype (creation through
delegation Delegation is the assignment of authority to another person (normally from a manager to a subordinate) to carry out specific activities. It is the process of distributing and entrusting work to another person,Schermerhorn, J., Davidson, P., Poole ...
). 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 Composite or compositing may refer to: Materials * Composite material, a material that is made from several different substances ** Metal matrix composite, composed of metal and other parts ** Cermet, a composite of ceramic and metallic materials ...
and decorator patterns often can benefit from Prototype as well. The rule of thumb could be that you would need to clone() an ''Object'' when you want to create another Object ''at runtime'' that is a ''true copy'' of the Object you are cloning. ''True copy'' means all the attributes of the newly created Object should be the same as the Object you are cloning. If you could have ''instantiated'' the class by using ''new'' instead, you would get an Object with all attributes as their initial values. For example, if you are designing a system for performing bank account transactions, then you would want to make a copy of the Object that holds your account information, perform transactions on it, and then replace the original Object with the modified one. In such cases, you would want to use clone() instead of new.


Code samples


Pseudocode

Let's write an occurrence browser class for a text. This class lists the occurrences of a word in a text. Such an object is expensive to create as the locations of the occurrences need an expensive process to find. So, to duplicate such an object, we use the prototype pattern: class WordOccurrences is field occurrences is The list of the index of each occurrence of the word in the text. constructor WordOccurrences(text, word) is input: the ''text'' in which the occurrences have to be found input: the ''word'' that should appear in the text Empty the ''occurrences'' list for each in text g:= true for each in word if the current word character does not match the current text character then g:= false if is true then Add the current into the ''occurrences'' list method getOneOccurrenceIndex(n) is input: a number to point on the ''n''th occurrence. output: the index of the ''n''th occurrence. Return the ''n''th item of the ''occurrences'' field if any. method clone() is output: a WordOccurrences object containing the same data. Call clone() on the super class. On the returned object, set the ''occurrences'' field with the value of the local ''occurrences'' field. Return the cloned object. texte:= "The prototype pattern is a creational design pattern in software development first described in design patterns, the book." wordw:= "pattern"d searchEnginen:= new WordOccurrences(text, word) anotherSearchEngineE:= searchEngine.clone() ''(the search algorithm is not optimized; it is a basic algorithm to illustrate the pattern implementation)''


C# example

The concrete type of object is created from its prototype. MemberwiseClone is used in the Clone method to create and return a copy of ConcreteFoo1 or ConcreteFoo2. public abstract class Foo public class ConcreteFoo1 : Foo public class ConcreteFoo2 : Foo


C++ example

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


Java example

This pattern creates the kind of object using its prototype. In other words, while creating the object of Prototype object, the class creates a clone of it and returns it as prototype. The clone method has been used to clone the prototype when required. // Prototype pattern public abstract class Prototype implements Cloneable public class ConcretePrototype1 extends Prototype public class ConcretePrototype2 extends Prototype


PHP example

// The Prototype pattern in PHP is done with the use of built-in PHP function __clone() abstract class Prototype class ConcretePrototype1 extends Prototype class ConcretePrototype2 extends Prototype $cP1 = new ConcretePrototype1(); $cP2 = new ConcretePrototype2(); $cP2C = clone $cP2; // RESULT: #quanton81 // CONS: A1 // CONS: B1 // CONS: A2 // CONS: B2 // CLON: A2-C // CLON: B2-C


Python example

Python version 3.9+ import copy class Prototype: def clone(self): return copy.deepcopy(self) if __name__

"__main__": prototype = Prototype() prototype_copy = prototype.clone() print(prototype_copy)
Output: <__main__.Prototype object at 0x7fae8f4e2940>


See also

* Function prototype


References

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