jeudi 24 août 2017

Factory Method pattern - what for this pattern is necessary?

I have abstract class-factory Factory with factory-method getProduct() and his child classes.

I have abstract class-product Product and his child classes.

Classes-factories created objects of classes-products.

abstract class Factory {
    abstract function getProduct();
}
class FirstFactory extends Factory {
    public function getProduct() {
        return new FirstProduct();
    }
}

abstract class Product {
};
class FirstProduct extends Product {
}

In result I can use this client code:

$factory = new FirstFactory();
$firstProduct = $factory->getProduct();
$factory = new SecondFactory();
$secondProduct = $factory->getProduct();

Question: what for this pattern is necessary? Because in client code I just can use direct classes:

$firstProduct = new FirstProduct();
$secondProduct = new SecondProduct();

Aucun commentaire:

Enregistrer un commentaire