Prototype

Prototype

  • prototypes design pattern allows you to create objects by cloning an existing object instead of creating a new object from scratch.
  • This pattern is used when the process of object creation is costly
  • when cloning, the newly copied object contains the same characteristics as its source object.
  • After cloning, we can change the values of the new object’s properties as required

Advantages of Prototype Pattern

  • By cloning, it cut down the resource consumption of object creation.
  • Clients can get new objects, without knowing which type it belongs to.
  • It allows you to add or remove objects at runtime.
  • It reduces the need for sub-classing.

When to use Prototype Pattern?

  • When the process of making an object is expensive or takes a long time.
  • When the client application must be unaware of the creation of an object.
  • When you need to keep the number of classes in your application to a minimum level.
  • When the classes are instantiated at runtime.

implementation of Prototype pattern

  • Let's take a simple scenario Shape and apply the prototype pattern
from abc import ABC
from copy import deepcopy

class Shape(ABC):

    def clone(self):
        return deepcopy(self)


class Circle(Shape):
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius**2

# client
if __name__ == '__main__':
    c1 = Circle(10)
    c1_copy = c1.clone()
    print(id(c1) == id(c1_copy))
    # False

In python, we have copy and deepcopy methods in the module copy which are used to copy the object.

References: