Design Patterns Java - Prototype Php

1) What has changed ?

"Product" types has been enriched on implementing interface "Cloneable" which has method "clone" for cloning oneself.

Product:

abstract class Product implements Cloneable
{
    @Override
    protected Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }
}

public class Product1 extends Product
{
}

public class Product2 extends Product
{

}




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

We add setter to inject "prototype" object


public class Creator
{
    Product product;

    public void setProduct(Product product)
    {
        this.product = product;
    }

    Product createProduct()
    {
        Product product = null;
        try
        {
            product = (Product) this.product.clone();
        } catch (CloneNotSupportedException e)
        {
            e.printStackTrace();
        }

        return product;
    }
}




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

java -Dtype=1 Main
java -Dtype=2 Main

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

public class Main
{
    public static void main(String[] args)
    {
        Creator creator = new Creator();
        Product prototype = System.getProperty("type", "1").equals("1") ? new Product1() : new Product2();
        creator.setProduct(prototype);
        Client client = new Client(creator);

        System.out.println((client.doSomethingAndReturnProduct() instanceof Product1) +
                        " " +
                        (client.doSomethingAndReturnProduct() instanceof Product2)
        );
    }
}


public class Client
{
    Creator creator;

    public Client(Creator creator)
    {
        this.creator = creator;
    }

    public Product doSomethingAndReturnProduct()
    {
        Product product = this.creator.createProduct();

        // some code

        return product;
    }
}



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

2) Let's summarize Prototype vs 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"