Design Patterns interview question · Most asked

Explain the Factory Method pattern and how it differs from a simple factory.

Summary

Factory Method lets subclasses decide which product to create by overriding a creation method that a shared algorithm calls. A simple factory is one function or class with a conditional that returns the right object; it isn't a GoF pattern but solves the same 'who decides the class' problem without subclassing.

Longer Answer

In Factory Method, the creator's algorithm (export()) calls create_formatter(); CsvReport and JsonReport override it. The algorithm only depends on the product interface, so new products need no changes to it. It suits frameworks where users extend a base class.

A simple factory (create_formatter("csv"), or a dictionary from names to classes) is more common in application code. With first-class functions, passing the product or a function that creates it is often simplest.

Code Example

class Csv:
    def format(self, row):
        return ",".join(row)


class Pipe:
    def format(self, row):
        return " | ".join(row)


class Report:
    def create_formatter(self):  # the factory method
        raise NotImplementedError

    def export(self, row):
        return self.create_formatter().format(row)


class CsvReport(Report):
    def create_formatter(self):
        return Csv()


class PipeReport(Report):
    def create_formatter(self):
        return Pipe()


for report in [CsvReport(), PipeReport()]:
    print(report.export(["1", "Ada"]))

Key Points

  • Creator calls an overridable creation method.
  • Subclasses choose the concrete product.
  • Simple factory = one creating function/lookup.
  • Java's Collection.iterator() is a factory method.

Deep dive: Design Patterns, Explained Simply: Factory Method

Explanation

What interviewers look for

Correct roles (creator, factory method, product) and the distinction from a simple factory.

Follow-up questions

  • When would you prefer a dictionary of constructors?
  • How does Factory Method support Open/Closed?

More most-asked Design Patterns questions

← All Design Patterns questions