design patterns · medium
GoF Factory Method — Deferred Object Creation via Subclasses
The Factory Method pattern separates object creation from the client that uses the object. An abstract Creator class declares a virtual factory method (e.g., createButton()); concrete subclasses (WindowsFactory, MacFactory) override it to return their specific concrete Product (WindowsButton, MacButton). The client depends only on the abstract Creator and abstract Product interfaces — never on concrete classes. Adding a new platform means adding a new Creator+Product pair with zero changes to existing code (Open/Closed Principle). Factory Method is often called inside a Template Method in the abstract Creator. Contrast with Abstract Factory (creates families of related objects) and Builder (step-by-step construction of a complex object).
Factory Method: define a virtual createProduct() in an abstract Creator; concrete subclasses override it to instantiate their specific Product; client code depends only on abstract interfaces, never uses new ConcreteClass directly — satisfies OCP.
The code
// Abstract Productclass Button {public: virtual void render() = 0; virtual ~Button() = default;};
// Concrete Productsclass WindowsButton : public Button { void render() override { /* Windows-style render */ }};class MacButton : public Button { void render() override { /* Mac-style render */ }};
// Abstract Creator with factory methodclass UIFactory {public: virtual Button* createButton() = 0; // <-- FACTORY METHOD void renderUI() { auto b = createButton(); // polymorphic creation b->render(); // client never knows which class }};
// Concrete Creatorsclass WindowsFactory : public UIFactory { Button* createButton() override { return new WindowsButton(); }};class MacFactory : public UIFactory { Button* createButton() override { return new MacButton(); }};
// Client: zero dependency on concrete classesUIFactory* f = getFactory(os); // dependency injectionf->renderUI(); // polymorphic — no switch, no new WindowsButtonWhat this lesson walks through
- 01The problem: switch-on-type in client code (anti-pattern)
- 02Factory Method: two parallel hierarchies
- 03WindowsFactory creates WindowsButton — client sees only Button*
- 04MacFactory creates MacButton — same client code, different result
- 05renderUI() template method — factory method called internally
- 06Key interview takeaways — Factory Method
Without Factory Method, the client code has a switch (or if-else chain) that decides which concrete class to instantiate. Every time you add a new platform, you must edit this switch — violating the Open/Closed Principle. The client is tightly coupled to every concrete class.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of GoF Factory Method — Deferred Object Creation via Subclasses and 100+ animated C++ interview lessons.