Prototype Pattern

Prototype Pattern

Prototype(clone) pattern allows copying an object using a prototypical instance

Prototype(clone) pattern allows copying an object using a prototypical instance

Motivation

Consider an application which requires using the same object numerous times. To create an exact clone of the existing object, you could create a new instance from the class and copy all the values. But this creates a problem if the object contains private properties and methods, so an exact copy might not be possible. In some cases, you might only know the interface and not the concrete class of the object.

The Prototype pattern solves this problem by implementing a clone method that allows creating an exact copy of an existing object without being dependent on the class of the object.

Applicability

The Prototype pattern can be used in cases where:

  • duplicating an object is favorable instead of building from scratch
  • the code is independent of any other third-party code

Structure

Prototype pattern class diagram

Participants

  • Prototype: declares an interface for cloning itself
  • ConcreteProtoype: implements cloning operation
  • Client: creates a new object by asking a prototype to clone itself

Collaborations

  • A client initiates the prototype clone operation

Advantages

  • Allows clients to add and remove prototype at run-time by registering a prototypical instance.
  • Allows us to avoid subclass hierarchy by using clone method.

Disadvantages

  • Cloning might be difficult when the existing class internals doesn’t support cloning or if there is a complicated nested structure.

Implementation

It is common to implement the prototype pattern using a prototype manager. A prototype manager is an associative store that returns the prototype matching a given key.

Demo

The waiters that serve at the cafe all have the same uniform and salary but different tables. The owners of the cafe want an easy way of getting new waiters, without going through the trouble of starting from scratch.

To solve this problem, we first create an abstract Prototype class with a copy method to enable cloning the object. We then create a Waiter class extending the Prototype class, implementing the cloning method. After that we create a WaiterFactory class that will use a Waiter object as a preset and clone it with different table numbers.