I'm trying to understand the advantages of the Factory Method pattern over a slightly modified simple factory. Using an example inspired by Head First Design Patterns, I have two pizza factories: NewYorkPizzaFactory and ChicagoPizzaFactory, both implementing a PizzaFactory interface with a method to create a pizza based on the type passed in. I believe this design, which uses composition instead of inheritance, is better, but I'm unsure about the benefits of the Factory Method pattern. Can anyone clarify?
3 Answers
Your pseudocode might be a bit off. Typically, a `createPizza` method shouldn't take a type parameter; it should directly create the pizza corresponding to its class. The main point when comparing your example to a normal factory method is determining where to decide which pizza factory your object needs. In a standard factory pattern, you would call a `createPizza` method and pass in the type, potentially using dependency injection to choose the right factory at runtime instead of locking it down in the factory itself.
Your example actually aligns more with the Abstract Factory pattern rather than a simple factory. The Abstract Factory has its advantages but sometimes you just want a simpler setup without needing custom factories provided by the user, hence a basic static method for factory creation can suffice.
Actually, the switch statement belongs in the interface, not in the concrete factory classes. You don't necessarily need inheritance with the factory method; it's about defining an interface for creating objects while letting subclasses decide which class to instantiate. This way, you avoid modifying the code every time a new pizza type is introduced or an old one is removed—something your method might run into.
I get that, but according to the GoF definition, it sounds like the idea is to have subclasses handle instantiation to promote flexibility, rather than using a switch in the superclass.
I see your point about the `createPizza` method. But just to clarify, my intention was to allow for creating different New York or Chicago pizzas by passing a type.