The Prototype pattern allows objects to copy or clone themselves rather than being instantiated, making dynamic object creation easier. It is used when you need to copy an existing object rather than creating a new instance of it, or when objects must have one of a limited set of configurations. With the Prototype pattern, a prototype declares an interface for cloning itself and concrete prototypes implement cloning. A client creates a new object by asking a prototype to clone itself, either as a shallow or deep copy.
Powerful Google developer tools for immediate impact! (2023-24 C)
Prototype_pattern
1. Prototype Pattern
● One of Creational Patterns
● Others: Singleton, Factory Method, Abstract
Factory, Builder
2. Purpose
To make dynamic creation easier by defining
classes whose objects can create
duplicates of themselves.
3. Motivation
Sometimes, it becomes necessary to copy
or clone an “already grown” object rather
than instantiating it and setting its values.
4. Applicability
- Use the Prototype pattern when you want to create an
object that is a copy of an existing object.
- When instances of a class can have one of only a few
different combinations of state.
6. Participants
Prototype declares an interface for cloning
itself.
ConcretePrototype implements an
operation for cloning itself.
Client creates a new object by asking a
prototype to clone itself.
9. Shallow vs Deep Copy
● A shallow copy duplicates only the top-level
elements of a class; this provides a faster copy, but
isn’t suitable for all needs.
● Deep copy operations replicate not only the top-level
attributes, but also the lower-level objects. This
typically takes longer than shallow copy operations,
and can be very costly for objects with an arbitrarily
complex structure.
10. Related Patterns
● Abstract Factory – Abstract Factories can
use the Prototype to create new objects
based on the current use of the Factory.
● Factory Method – Factory Methods can
use a Prototype to act as a template for
new objects.
11. Pros and Cons
Pros:
● Hides the complexities of making new instances from
the client.
● In certain circumstances, copy an object is more
efficient than creating a new object
● Using a Prototype design pattern hides concrete
product classes from the client
Cons:
● Classes can be difficult to deep clone