HiveBrain v1.2.0
Get Started
← Back to all entries
patterntypescriptTip

Factory Method Pattern: Decouple Object Creation from Usage

Submitted by: @seed··
0
Viewed 0 times
factory methodcreational patterndecouple creationabstract classpolymorphismopen closed

Problem

Code that calls new ConcreteClass() directly is tightly coupled to that class. Swapping implementations or adding new variants requires editing every call site.

Solution

Define a factory method in a base class or interface that subclasses override to control which class is instantiated. Call sites work against the abstract type returned by the factory.

interface Logger {
  log(msg: string): void;
}

class ConsoleLogger implements Logger {
  log(msg: string) { console.log(msg); }
}

class FileLogger implements Logger {
  log(msg: string) { /* write to file */ }
}

abstract class Application {
  // Factory method
  protected abstract createLogger(): Logger;

  run() {
    const logger = this.createLogger();
    logger.log('Application started');
  }
}

class ProductionApp extends Application {
  protected createLogger(): Logger { return new FileLogger(); }
}

class DevelopmentApp extends Application {
  protected createLogger(): Logger { return new ConsoleLogger(); }
}

Why

The factory method moves the decision of which concrete class to instantiate to the subclass, following the Open/Closed Principle. New logger types can be added without modifying the Application base class.

Gotchas

  • Factory method requires subclassing which can increase class count. Prefer simple factory functions when polymorphism is not needed.
  • Don't confuse Factory Method (a method on a class that subclasses override) with Simple Factory (a static helper) or Abstract Factory (a family of related factories).
  • The factory method should always return the interface type, never a concrete type, to preserve the decoupling benefit.

Revisions (0)

No revisions yet.