Design patterns: Prototype

date: · 3 min
author: Mauto
series: Design Patterns/ part 6/24

The classic Gang of Four patterns, one per part, with practical PHP examples.

  1. Design Patterns
  2. Design patterns: Singleton
  3. Design patterns: Factory Method
  4. Design patterns: Abstract Factory
  5. Design patterns: Builder
  6. Design patterns: Prototype
  7. Design patterns: Adapter
  8. Bridge Pattern in PHP: What It Is, When to Use It, with Examples
  9. Design patterns: Composite
  10. Design patterns: Decorator
  11. Design patterns: Facade, What It Is and How to Use It (PHP)
  12. Design patterns: Flyweight
  13. Design patterns: Proxy
  14. Design patterns: Chain of Responsibility Explained (PHP)
  15. Design patterns: Command
  16. Design patterns: Interpreter
  17. Design patterns: Iterator
  18. Design patterns: Mediator
  19. Design patterns: Memento
  20. Design patterns: Observer
  21. Design patterns: State, What It Is and How to Use It (PHP)
  22. Design patterns: Strategy
  23. Design patterns: Template Method
  24. Design patterns: Visitor
the whole guide >

The Prototype pattern is a creational pattern that lets you create new objects by cloning an existing instance. This is useful when creating a new object requires significant resources and we can obtain new instances by cloning existing ones.

Characteristics of the Prototype pattern

  1. Object Creation Through Cloning: The Prototype Pattern lets you create new objects by copying (cloning) an existing object instead of instantiating it through a constructor. This is especially useful for complex objects.
  2. Independence of Clones: Prototype objects can be used as the basis for creating new objects. New objects created through cloning can be modified without altering the original prototype object. Note: in PHP clone makes a shallow copy, so properties holding objects must be cloned explicitly in __clone() (deep copy), otherwise the clone and the prototype share them.
  3. Independence from the Concrete Class: The pattern doesn’t require client code to know the concrete class of the objects it’s creating. It can interact with the objects through a common interface.
  4. Simpler Creation of Complex Objects: When an object is difficult or expensive to create, the Prototype Pattern lets you define a “template” object that can be cloned and customized.
  5. Efficiency: Cloning an object can be more efficient than creating a new one, especially if the construction process is complex and resource-intensive.
  6. Support for Dynamic Variation: It’s easy to change the configuration of a copied object without affecting the original prototype, giving you flexibility in managing objects at runtime.
  7. Less Reliance on Constructors: It reduces the need for multiple constructors for different objects, simplifying the code and improving maintainability.

PHP Example:

Imagine a system in which we can create different kinds of animals by cloning them from prototypes stored in a registry.

// Prototype interface
interface AnimalPrototype {
    public function __clone();
    public function getType();
    public function getName();
    public function setName($name);
}

// Concrete class for Sheep
class Sheep implements AnimalPrototype {
    private $type = "Sheep";
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getType() {
        return $this->type;
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function __clone() {
        // Scalar properties are copied automatically.
        // Any object properties should be cloned here (deep copy).
    }
}

// Concrete class for Cow
class Cow implements AnimalPrototype {
    private $type = "Cow";
    private $name;

    public function __construct($name) {
        $this->name = $name;
    }

    public function getType() {
        return $this->type;
    }

    public function getName() {
        return $this->name;
    }

    public function setName($name) {
        $this->name = $name;
    }

    public function __clone() {
        // Scalar properties are copied automatically.
        // Any object properties should be cloned here (deep copy).
    }
}

// Registry that stores the prototypes and returns clones
class AnimalRegistry {
    private $prototypes = [];

    public function addPrototype($key, AnimalPrototype $prototype) {
        $this->prototypes[$key] = $prototype;
    }

    public function create($key): AnimalPrototype {
        if (!isset($this->prototypes[$key])) {
            throw new InvalidArgumentException("Prototype not found: $key");
        }
        return clone $this->prototypes[$key];
    }
}

// Setup: the prototypes are created only once
$registry = new AnimalRegistry();
$registry->addPrototype("sheep", new Sheep("Dolly"));
$registry->addPrototype("cow", new Cow("Carolina"));

// Usage: the client asks the registry for a clone, without using "new"
$firstSheepClone = $registry->create("sheep");
$secondSheepClone = $registry->create("sheep");
$firstCowClone = $registry->create("cow");

// Change a clone: the prototype stays the same
$secondSheepClone->setName("Shaun");

echo "Cloned: " . $firstSheepClone->getType() . " " . $firstSheepClone->getName() . "\n"; // Cloned: Sheep Dolly
echo "Cloned: " . $secondSheepClone->getType() . " " . $secondSheepClone->getName() . "\n"; // Cloned: Sheep Shaun
echo "Cloned: " . $firstCowClone->getType() . " " . $firstCowClone->getName() . "\n"; // Cloned: Cow Carolina
echo "Prototype unchanged, new clone: " . $registry->create("sheep")->getName() . "\n"; // Prototype unchanged, new clone: Dolly

BACK TO THE GUIDE

Copied