Design patterns: Prototype

Mauto 2 min

The Prototype pattern 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. Immutability of Prototypes: 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.
  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.

// Prototype interface
interface AnimalPrototype {
    public function __clone();
    public function getType();
}

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

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

    public function __clone() {
        // We can add cloning logic here if needed
    }
}

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

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

    public function __clone() {
        // We can add cloning logic here if needed
    }
}

// Usage
$sheepPrototype = new Sheep();
$firstSheepClone = clone $sheepPrototype;
$secondSheepClone = clone $sheepPrototype;

$cowPrototype = new Cow();
$firstCowClone = clone $cowPrototype;

echo "Cloned: " . $firstSheepClone->getType() . "\n"; // Cloned: Sheep
echo "Cloned: " . $secondSheepClone->getType() . "\n"; // Cloned: Sheep
echo "Cloned: " . $firstCowClone->getType() . "\n"; // Cloned: Cow

BACK TO THE GUIDE

Copiato