Skip to content

Prototype

Roberto Fronteddu edited this page Jan 30, 2023 · 5 revisions

The Prototype Method is a Creational Design Pattern.

The idea is to reuse the instance of an already created class to expedite the creation of another object with a shared immutable state.

Usefull when

  • We have a complex object that is costly to create. To create more instances of such a class, we use an existing instance as our prototype.
  • Prototype will allow us to make copies of existing objects and save us from having to recreate objects from scratch.

Implementattion Steps

  1. Creating the Prototype class
    • it must implement the Cloneable interface
    • it must override the clone method and return a copy of itself
    • declare CloneNotSupportedException in the throws clause to give subclasses the chance to decide on whether to support cloning.
  2. The clone method implementation should consider whether a deep or shallow copy is applicable

Example

prototype-method-uml

  • Prototype: Declares a method for cloning itself
  • PrototypeA and PrototypeB: Implement the cloning method
  • Client: Creates a new instance of a prototype using prototypes' clone methods.

Design Considerations

  • Pay attention to the deep copy and shallow copy of references. Immutable fields on clones save the trouble of deep copy.
  • Make sure to reset the mutable state of a cloned object before returning the prototype. It's a good idea to implement a reset method to allow subclasses to initialize themselves.
  • The clone method is protected in the Object parent and must be overridden to be public to be callable from outside the class.
  • Useful when you have large objects where the majority of the state is unchanged between instances and you can easily identify that state.
  • A prototype registry is a class wherein you can register various prototypes which other code can access to clone out instances. This solves the issue of getting access to an initial instance.
  • Prototypes are really useful when working with composite and decorator patterns.

Comparison with Singleton

  • Singleton allows you to have only one instance of a class in your code. There is only one instance and state for the class.
  • Prototype: Returns a copy of an instance. The state of instances can be different.

Pitfalls

  • If the state of a class is made of a large number of mutable objects, the cloning process can be complicated since they all need to be deeply copied.
  • Default java clone only performs a shallow copy.

Real-Life Examples

  • Object.clone()
Clone this wiki locally