Sobes.tech
Middle

What is a Prototype design pattern?

sobes.tech AI

Answer from AI

Prototype is a creational design pattern that allows copying existing objects without delving into their implementation details.

Main ideas:

  • Cloning objects through a special interface (clone).
  • Creating a copy of an object without calling the class constructor.
  • Preserving the current state of the object during cloning.

Pros:

  • Allows creating new objects based on existing ones, which is convenient for complex object configurations.
  • Speeds up object creation compared to using the constructor, as it does not require initialization from scratch.
  • Hides the complexities of object creation from the client.

Cons:

  • Implementing deep copying can be complex.
  • When adding new fields to a class, the cloning method needs to be updated.

Example in Python:

import copy

class Prototype:
    def __init__(self, value):
        self._value = value

    def clone(self):
        # Return a shallow copy
        return copy.copy(self)

    def deep_clone(self):
        # Return a deep copy
        return copy.deepcopy(self)

    def __str__(self):
        return f"Prototype({self._value})"

# Usage example
original = Prototype([1, 2, [3, 4]])

# Shallow copy
shallow_copy = original.clone()
shallow_copy._value[2].append(5) # Changes in the copy affect the original
print(f"Original after shallow: {original}")
print(f"Shallow copy: {shallow_copy}")

# Deep copy
deep_copy = original.deep_clone()
deep_copy._value[2].append(6) # Changes in the copy do not affect the original
print(f"Original after deep: {original}")
print(f"Deep copy: {deep_copy}")