Prototype | Cheat Sheet

Creational Pattern — Design Patterns Series

Itchimonji
CP Massive Programming
3 min readJun 6, 2021

--

The Prototype pattern is also known as Cloning. It creates new objects by copying a prototypical instance. The new object differs only in few things from their predecessors, so it is unnecessary to declare concrete classes. This leads to a class mess.

Product addition and removal at runtime enables more flexibility to add new variants in the form of classes, minimizes maintenance effort, and reduces the need for factories.

Real-life examples

  • Cell division
  • Product manufacturing: new products often differ from their predecessors in only a few respects (cell phones, tablets, laptops, …)
  • Car production: with different extras (color, interior, rims, …)

Meaning

  • Specification of a prototypical instance
  • Creation of new objects by copying the prototype

Applicability

  • Classes to be instantiated are specified only at runtime (dynamic loading)
  • Avoidance of factories, because otherwise there are too many concrete classes
  • Instances have few state combinations

Assets and Drawbacks

  • Product addition and removal at runtime (more flexibility than other Creational Patterns)
  • Specification of new objects by means of value variation (and thus reduction of concrete classes)
  • Reduced subclassing

Example

Depending on your programming language or framework, there are differences between simple cloning and deep cloning. Simple cloning enables only copying attributes/properties. However, deep cloning makes it possible to copy attributes and methods. So, be sure you use the right one for your use case.

Deep cloning in TypeScript can be realized by the combination of Object.assign and Object.create. Alternatively you can use Lodash.

Car class that can clone itself

The Prototype interface and concrete class look very simple.

Prototype interface

The client can copy an old car easily and change some properties at the new one.

Client clones a car

Conclusion

Design Patterns are an important resource and base knowledge for every developer — they are very helpful for solving programmatic problems, help with consistent communication with other developers about system design, and are a significant introduction into object composition (besides inheritance) and dependency inversion.

Creational Patterns are indispensable when abstracting the instantiation process of objects. Of high importance are encapsulation of concrete classes and hiding the creational process.

--

--

Itchimonji
CP Massive Programming

Freelancer | Site Reliability Engineer (DevOps) / Kubernetes (CKAD) | Full Stack Software Engineer | https://patrick-eichler.com/links