A_G
A_G

Reputation: 2370

Demerit of declaring static method in AbstractFactory

The disadvantage of declaring static method in Factory class, according to Head First Design Pattern - "you can't subclass and change the behavior of getPizza method". getPizza method is used by Factory class to decide which type of object to return. If I understand correctly, my class is

    public class PizzaFactory {
        public static Pizza getPizza(String type) {
            if (type.equals("cheese"))
                return new CheesePizza();
            else if (type.equalsIgnoreCase("thisCrust"))
                return new ThinCrustPizza();
            return null;
        }
    }

Even though the method is static I can always create a subclass like -

public class DelhiPizzaFactory extends PizzaFactory {
    public static Pizza getPizza(String type) {
        if (type.equals("cheese"))
            return new CheesePizza();
        else if (type.equalsIgnoreCase("thisCrust"))
            return new ThinCrustPizza();
        return null;
    }
}

I can use both the superclass and subclass interchangeably.

public class PizzaStore {

    Pizza pizza;

    public void orderPizza(String type) {
        pizza = DelhiPizzaFactory.getPizza(type);
        pizza.prepare();
        pizza.bake();
    }
}

So what is the disadvantage?

Upvotes: 0

Views: 64

Answers (2)

Antoniossss
Antoniossss

Reputation: 32535

It is a matter of use case. Consider case, that you are using API that has the following method of some global API.

public void setPizzaFactory(PizzaFactory factory) {
    this.pizzaFactory=factory;
   // set pizza factory and 
}

Normally, you can pass both of your factories as argument to that method, but if our API will use the PizzaFactory you have just set, and call its getPizza() method, it will always use getPizza() method declared in PizzaClass despite the fact that you have probably passed some other derivered class as factory object.

If you would have nonstatic methods in your factory, then you could do something like that

api.setPizzaFactory(new DoubleCheesePizzaFactory) where DoubleCheesePizzaFactory overrides getPizza method to always add extra cheese to every pizza. This way, internal "baking" api will use getCheese method version from DoubleCheesePizzaFactory insteed of PizzaFactory.getPizza version (aka. super.getPizza)

So disatvantage is just like that: You cannot change the behaviour (by overridding) of methods that are in super class.

Upvotes: 3

Jonas Czech
Jonas Czech

Reputation: 12348

Since you want to prevent overriding, you'd need to make your method final, ie. like this:

public class PizzaFactory {
     public static final Pizza getPizza(String type) {
         [...]
}

This way, you can prevent overriding, if this is what you want in this case, although in other cases, yes, allowing overriding by not making it final can be useful too.

Upvotes: 0

Related Questions