Design Patterns PHP - Prototype Java

1) What are we going to start from ?

Let's imagine following class structure:
We have "Product" object and corresponding "Creator" objects which creates "Products"

Product:

interface Product
{
}

class Product1 implements Product
{

}

class Product2 implements Product
{

}




Creator:

abstract class Creator
{
    /**
     * @return Product
     */
    abstract function createProduct();

}

class Creator1 extends Creator
{
    /**
     * @return Product
     */
    function createProduct()
    {
        return new Product1();
    }
}

class Creator2 extends Creator
{
    /**
     * @return Product
     */
    function createProduct()
    {
        return new Product2();
    }
}




The solution is quite good in application we can easily creates appropriate products using "Creators".


$product = $creator->createProduct();




But we need to notice that for class hierarchy of "Product"("Product1" and "Product2") we need to create corresponding hierarchy of "Creator" class("Creator1" and "Creator2").

2) Is exist some alternative solution?

Yes and it's called "Prototype" pattern.

In this pattern we won't create any more for every "Product" implementation corresponding "Creator" implementation.

The solution is that we inject to "Creator" one "Product" object which we call "prototype" and then we are going to clone this instance of "Product"

Let's see this in step 2 how it is implemented