CSE Roadmap

Core tier · about 3 hours · 6 parts

Part 5 of 6 · 3 min read

The Factory Method pattern

Let subclasses decide what to create.

The Factory Method pattern

GoF defines Factory Method as an interface for creating an object, where subclasses decide which class to instantiate. It lets a class defer instantiation to subclasses. GoF also calls it a "virtual constructor".

GoF's motivating case is a framework. An Application class manages Document objects and knows when to create a new one, for example when the user chooses New. It cannot know which document class a particular application needs. So Application declares an abstract createDocument method, and each application subclass overrides it to return its own document type.

The same shape in our booking world: a checkout flow is the same everywhere, but the receipt differs by country.

interface Receipt { String text(); }
class PlainReceipt implements Receipt { public String text() { return "plain receipt"; } }
class GstReceipt   implements Receipt { public String text() { return "receipt with GST"; } }

abstract class Checkout {
    abstract Receipt createReceipt();          // the factory method

    String finish() {
        Receipt r = createReceipt();
        return "paid; " + r.text();
    }
}

class IndiaCheckout   extends Checkout { Receipt createReceipt() { return new GstReceipt(); } }
class DefaultCheckout extends Checkout { Receipt createReceipt() { return new PlainReceipt(); } }

new IndiaCheckout().finish() returns "paid; receipt with GST". new DefaultCheckout().finish() returns "paid; plain receipt". The finish method is written once and never names a receipt class.

GoF names the parts. The Product is the interface of the made object (Receipt). A ConcreteProduct implements it. The Creator declares the factory method (Checkout), and may call it. A ConcreteCreator overrides it. GoF says the creator may also give the method a default body that returns a default product.

GoF lists the consequences. Factory methods remove the need to bind application-specific classes into the code, which only deals with the product interface. They give subclasses a hook to provide an extended object. The disadvantage is that a client may have to subclass the creator just to get a particular product, which adds another point of change. GoF adds that Factory Method is often the default way to create objects, though it is not needed when the class that gets instantiated never changes. It also notes that many designs begin with Factory Method and later move to the other creational patterns, once the designer sees where more flexibility is needed.

Choosing between the three:

Need Use
Clear names, caching, hiding classes Static factory method
One place that picks a class from a code or setting Simple factory
A fixed algorithm where a subclass picks the product Factory Method

Interview angle

Answer in your head first, then open it.

What is the Factory Method pattern?

A creator class declares a method that returns a product interface, and subclasses override it to choose the concrete class.

How does it differ from a simple factory?

A simple factory is one class with a switch. Factory Method uses inheritance, so adding a new product means adding a new subclass.

Give a real example.

Collection.iterator() is a factory method that each collection implements to return its own iterator.

Check yourself: 1. What does new IndiaCheckout().finish() return? 2. In GoF's terms, which class is the Creator here? 3. What is a disadvantage of Factory Method?

Words you will meet

Word Meaning
Static factory method A static method that returns an instance, with a descriptive name
Simple factory A class that makes objects of related types by a code
Factory Method A pattern where subclasses choose the class to create
Product The interface of the object being made
Creator The class that declares the factory method