Skip to content
ilyana.dev
TwitterGithubLinkedIn

The Prototype Pattern

software development, coding, pluralsight, design patterns1 min read

prototype pattern

The Prototype Pattern is designed to reduce the overhead of creating a new object by cloning an existing object rather than initiating a new object.

Head First Design Patterns by Eric Freeman and Elisabeth Freeman provides a quick overview of the Prototype Pattern in its appendix.

Pluralsight's Design Patterns Library course has a module on the Prototype Pattern from John Sonmez.

The Prototype Pattern is all about making a copy of or cloning an existing object instead of newing up an object.

Sonmez makes the comparison: if you need a second copy of a bill, document, flyer, etc., you don't call up whoever sent you that piece of paper and ask for another one; you just put it on the copy machine! That's exactly what the Prototype Pattern does; instead of going through all the processes needed to construct an object from scratch, you just make a copy of an existing object.

Implementation

In the Prototype Pattern, the client depends upon a prototype interface, which defines a method for an object copying itself. Various concrete prototypes inherit from that prototype interface; these concrete prototypes must implement a method for copying themselves. This copying method can be implemented as a deep copy (copy everything) or a shallow copy (copy the important stuff).

Application

The Prototype Pattern should be considered if object contstruction is expensive, state is important, and/or the object's constructor should be hidden.

In the real world, JavaScript is designed based on prototypes.

Both C# and Java have built-in cloning support through the IClonable C# interface and Clonable Java interface.

Thanks for reading! I hope you find this and other articles here at ilyanaDev helpful! Be sure to follow me on Twitter @ilyanaDev.