HuntExams Academy logo
JavaIntermediate#design-patterns

What is the Factory design pattern?

Answer

A creational pattern that defines a method for creating objects without exposing the exact instantiation logic to the client, letting subclasses or a factory method decide which concrete class to instantiate.

Example

interface Shape { void draw(); }
class Circle implements Shape { public void draw() { System.out.println("Circle"); } }
class ShapeFactory {
  static Shape create(String type) {
    return switch (type) { case "circle" -> new Circle(); default -> null; };
  }
}

Detailed explanation

The Factory design pattern is a creational approach that separates object creation from the code that uses those objects. Instead of directly calling a concrete class constructor, the client asks a factory for an object and works through an interface or superclass. This reduces coupling to concrete implementations and gives construction decisions a clear home. It is useful when implementations depend on configuration, input, or runtime conditions, or when construction requires validation and setup that should not be repeated across clients.

In the example, Shape is the common interface, Circle is a concrete implementation, and ShapeFactory.create("circle") returns a Shape reference holding a Circle object. The factory examines the type argument and executes the appropriate constructor. The client can then call draw() without knowing how the object was instantiated; Java's runtime method dispatch selects Circle.draw(). The factory does not eliminate concrete dependencies altogether: it moves them from client code into the creation layer. Also, factories do not necessarily create a fresh object every time; their contract may allow cached or shared instances.

An important interview distinction is that the supplied example is a Simple Factory, not the classic Gang of Four Factory Method pattern. A Simple Factory typically uses one method with conditional logic to choose an implementation. Factory Method defines a creation method in a creator class and lets subclasses override it to select the product. For example, an abstract DrawingApplication could declare createShape(), while CircleApplication overrides it to return a Circle. Shared application logic calls createShape() and uses the returned Shape. Abstract Factory is another related pattern: it creates families of related products rather than just one product abstraction.

Interviewers usually look for the purpose, participants, and trade-offs rather than only a memorised definition. Adding a Square to this Simple Factory requires another branch, whereas Factory Method can introduce a new creator subclass without editing existing creator logic. Neither approach automatically makes every design extensible. Returning null for an unsupported type is risky because failure occurs later; throwing IllegalArgumentException gives a clearer error. Prefer a factory when it meaningfully simplifies creation, not when it merely wraps an already obvious constructor call.

Key points to remember

  • Factories separate creation decisions from client behaviour and return an abstraction.
  • Clients still depend on the product interface and a creation entry point.
  • The supplied static switch-based implementation is a Simple Factory.
  • Classic Factory Method uses an overridable creation method and creator subclasses.
  • Choose explicit failure behaviour for unsupported inputs rather than silently returning null.

Common mistakes candidates make

  • Calling every static creation method an implementation of the classic Factory Method pattern.
  • Claiming factories remove all concrete dependencies or always return new instances.
  • Adding factories everywhere without explaining the construction complexity or variation they address.

Likely follow-up questions

How is Factory Method different from Abstract Factory?

Factory Method delegates product creation through an overridable method, commonly using creator subclasses. Abstract Factory provides an interface for creating a family of related products, such as matching buttons and menus for a UI theme.

How would you improve the given ShapeFactory?

Throw IllegalArgumentException for unsupported types and define how null input is handled. For a fixed set of choices, an enum can replace fragile string identifiers; larger designs may benefit from a registry of suppliers.

When should you use a factory instead of a constructor?

Use a factory when callers should not choose the concrete class or when creation involves meaningful selection, validation, or reuse. A direct constructor is simpler when the implementation is known and construction is straightforward.

Interview tip: Define the purpose first, trace the Shape example, and then explicitly distinguish Simple Factory from Factory Method.

Related Interview Questions

1
JavaIntermediate#design-patterns

What is the Builder pattern and when should you use it?

Open
2
JavaIntermediate#design-patterns

What is the Observer pattern?

Open
3
JavaIntermediate#design-patterns

What is the Strategy pattern?

Open