Prototype

Creational pattern

The Prototype pattern functionality is based on object cloning. New objects are created from a pool of previously created and stored prototypes. This pattern is especially useful when we need to create objects from existing ones or for creating very large structures of objects. This pattern also helps us hide the strategy we used for cloning objects from the user.

Prototype design pattern structure.
Prototype design pattern structure.

The components included in this pattern are:

  • Client: The component which interacts with the prototypes.
  • IPrototype: This component is typically an interface which defines the minimum attributes of a prototype. This interface should have at least one of these two cloning types: Shallow cloning (clone) or Deep cloning (deepClone) which will be explained later.
  • ConcretePrototype: Concrete implementations of the IPrototype objects, which can be cloned.
  • PrototypeFactory: This is the component we will use for keeping a cache of existing prototypes in order to make clones from them.

Real-world example

By implementing the Prototype design pattern, we are going to clone an entire list of products in order to create others from it. How many times have we seen companies working with more than one price list, which must be created from scratch and then filled up with the same products from the original? Wouldn't it be better to use a price list as a template for creating new lists with different discounts?

Discover how the Prototype pattern can help us solve this problem.
Discover how the Prototype pattern can help us solve this problem.

About this book

Introduction to design patterns

Everything you just saw in this article is only a small part of the book Introduction to design patterns, the most complete book of design patterns in Spanish, we cover 25 design patterns along with 25 real-world projects. Forget about learning design patterns with typical Internet examples of how to make pizza, animals, and geometric shapes. I invite you to see my book:

See book
All rights reserved ©
Reactive programming
LinkedinYoutubeTwitterFacebook

© 2021, Copyright - Oscar Blancarte. All rights reserved.