Factory Method

If our requirements for a factory are not too demanding, we could use the simple factory pattern we have seen in the previous post. But usually is better to think to the Factory Method Pattern. Here are a few hotes I have jotted down while reading the second part of chapter four of Head First Design Patterns, by Freeman, Freeman, Sierra, Bates. Get the book for more details.

Let's think the case where our application has to manage not a single pizza store but a chain of them, where each one should be able to create each pizza based not only on its own type but also on the store location.

TO do that, we'd better move the factory capability to an abstract method of the PizzaStore class, implementing it accordingly to the local requirements.

That will be now our class:
public abstract class PizzaStore {
    public Pizza orderPizza(String type) {
    Pizza = createPizza(type);

    // ...

    return pizza;

    abstract Pizza createPizza(String type);
Any concrete pizza store now owns the factory methods that knows how to create its specific pizza. The recipe is the same for all the pizza stores, so it is kept in the orderPizza() method available in the base class, but the actual pizza is going to be generated based on to the local store requirements.

Generically speaking, the trick is to declare in the base class an abstract method that provides the signature that has to be respected by all the concrete classes for the factory method:
abstract Product factoryMethod(/*...*/);
So we can say that the Factory Method pattern is about defining an interface for creating a Product in a base class, and letting the derived classes to decide which actual concrete Product instantiate. The instantiation of the product is deferred to the subclass.

No comments:

Post a Comment