Skip to content

Creational Design Pattern: Prototype Pattern

Prototype Pattern is an creation pattern based on cloning a pre-configured object. The idea is that you pick an object that is configured for either the default or in the ballpark of some specific use case and then you clone this and configure to your exact needs. The pattern is useful to remove a bunch of boilerplate code, when the configuration required would be onerous. We can think of Prototypes as a preset object, where you save a bunch of state as a new starting point.

Example

Let’s take a look at a abstract example to get a grasp of the topic:

Prototype Pattern UML diagram
Prototype Pattern UML diagram

Lets see the code to understand the logic more clearly.

In the above Code few things can be seen in much clearer sense:

  1. Concrete Prototype class implements Prototype interface.
  2. Prototype Provider class keeps pre-configured instances of Concrete Prototypes.
  3. Every time a new object of one of the pre-configured type is required rather then going and creating a new object and then initialize it to pre-configured values, we get a clone of them.
  4. Cloning is always faster then creating a new object using the “new” keyword.

Now last we’ll see how it will be used on the client side code.

This concludes the prototype pattern. Client code does not bother to create a new object and then configure it to desired need on the contrary it gets a cloned object instantly. Bunch of boiler-plate code to initialize the states of pre-configured objects are also gone thus making a cleaner and less error-prone code.

Advantages of Prototype Pattern

  1. Creates deep copy of complex object hierarchy.
  2. Reduced load of initialization. Cloning object I always more efficient then creating a new object by using new operator.
  3. Simplified copy process. Creating objects that have some preset values again and again adds more boilerplate code which is always bad for reusability, maintained and readability.

Disadvantages of Prototype Pattern

  1. A copy of all objects that supports prototyping must exists in memory for prototyping to work.

I hope you made some sense out of this Pattern.
As always thank you for reading.
Cheers!!

Published inDesign Patterns

Be First to Comment

    Leave a Reply

    Your email address will not be published. Required fields are marked *