Design Patterns PHP - Prototype Java

1) What has changed ?

"Product" types has been enriched on implementing interface "Prototype" which has method "copy" for cloning oneself.

Prototype:

interface Prototype
{
    /**
     * @return Prototype
     */
    public function copy();
}

trait PrototypeImpl
{
    /**
     * @return Product
     */
    public function copy()
    {
        return clone $this;
    }
}




and Product:

interface Product extends Prototype
{
}

class Product1 implements Product
{
    use PrototypeImpl;
}

class Product2 implements Product
{
    use PrototypeImpl;
}




2) We now have only one Creator implementation of "Creator"

We add setter to inject "prototype" object


class Creator
{

    /**
     * @var Prototype
     */
    protected $prototype;

    /**
     * @return Product
     */
    function createProduct()
    {
        return $this->prototype->copy();
    }

    /**
     * @param Prototype $prototype
     */
    public function setPrototype($prototype)
    {
        $this->prototype = $prototype;
    }


}




And depending on "type" parameter we injecting appropriate prototype to "Creator"

php main.php --type=1
php main.php --type=2

Creating "Product" instances it just creating clones of prototype.


function __autoload($class_name)
{
    include $class_name . '.php';
}

$opt = getopt('', array('type:'));
$type = isset($opt['type']) ? ($opt['type'] == 2 ? 2 : 1) : 1;


$prototypeOfProduct1 = new Product1();
$prototypeOfProduct2 = new Product2();


$creator = new Creator();
$creator->setPrototype(${'prototypeOfProduct' . $type});


include 'Client.php';

var_dump($product);

$product = $creator->createProduct();




That's all. It's whole philosophy of this pattern.

2) Let's summarize Prototype and FactoryMethod

- In "Prototype" "Products" have to implement addition method for cloning
- In "Prototype" we have only one implementation of "Creator" we don't have to reproduce whole hierarchy of "Product"