Design Patterns

Factory Method



Design Pattern Type: Creational

GoF Statement of Intent:


Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses.
Brief Overview:



One of the creational patterns. This pattern focuses on the creation of objects without specifying the exact class of the object to be created. Like other creational patterns this is done by defining a separate function to handle creating objects. Subclasses then override this method to instantiate the appropriate object.
UML Diagram:

Discussion and In-class Example:

In the Factory Method Design Pattern we used the example of the PizzaShop which had several subclasses defining the style of pizzas they prepared. As the types and styles of pizzas expanded it became increasingly difficult to maintain the code to build the correct pizza type. As a solution we removed the pizza creation functionality from the parent class (PizzaShop) and encapsulated it in the subclasses via the virtual function createPizza() inherited from the parent.



Now with the appropriate subclasses of Pizza types (cheese, pepperoni, clam (yuk!), and Veggie) for each of the styles (New York, Chicago, and California) for example NYStyleCheesePizza, NYStylePepperoniPizza, NYStyleClamPizza, and NYStyleVeggiePizza for the NYPizzaShop we could defer to the subclasses of PizzaShop the creation of their appropriate style of pizza for each of the types available.

Here the PizzaShop class defines a method createPizza() but lets the subclasses handle the style of pizza (New York style by the NYPizzaShop, Chicago style by the ChicagoPizzaShop, and California style by the CaliforniaPizzaShop).