Design Patterns Java - Prototype Php

1) Where to begin?

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

Product:

public interface Product
{
}

public class Product1 implements Product
{
}

public class Product2 implements Product
{
}




Creator:

interface Creator
{
    Product createProduct();
}

public class Creator1 implements Creator
{
    @Override
    public Product createProduct()
    {
        return new Product1();
    }
}

public class Creator2 implements Creator
{
    @Override
    public Product createProduct()
    {
        return new Product2();
    }
}




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


public class Client
{
    Creator creator;

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

    public void doSomething()
    {
        // some code

        Product product = this.creator.createProduct();

        // some code
    }
}




But let's notice that for hierarchy class 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