Design Patterns PHP - Factory Method Java

1) What have we changed ?

We created abstract class "Creator" and two inheriting classes "Creator1" and "Creator2" which return appropriate implementation of "Product"


abstract class Creator
{
    /**
     * @var Registry
     */
    protected $registry;

    function __construct(Registry $registry)
    {
        $this->registry = $registry;
    }

    abstract public function getProduct();

}

class Creator1 extends Creator
{

    public function getProduct()
    {
        $product = new Product1();
        $this->registry->addProduct($product);
        return $product;
    }
}

class Creator2 extends Creator
{

    public function getProduct()
    {
        $product = new Product2();
        $this->registry->addProduct($product);
        return $product;
    }
}




2) Whether this solution has drawbacks ?

Seems that now everything is fine but let's consider method "getProduct" in class "Creator1" and "Creator2"

We have the repetition code of adding to registry.

Let's imagine that in real situation we have not only adding to registry but much more actions. We must to repeat this in two classes.
Definitely we need to get rid of this duplication.

3) How we can improve this ?


It is here that comes to our rescue Factory Method pattern

We change only this that instead of call constructor in method "getProduct" we create special abstract method for returning appropriate object.
And thereby method "getProduct" we can move up to abstract class "Creator"