Zachary W. Huang

Home Projects Blog Guides Resume

Factory Method

Idea: Allows an abstract class to create a product, even if it does not yet know its concrete class. Essentially, it defers (delegates?) to the subclass to determine which concrete product to create.

Note: Subclassing may not be necessary, depending on the language. For example, you could get the same behavior in C++ by using templates to parameterize Creator on a concrete Product class. This pattern is common toolkits and frameworks, and it is used in Abstract Factory.

abstract class Product {
  abstract doThing(): void;
}

abstract class Creator {
  // Overriden by subclass
  abstract createProduct(): Product;

  methodThatNeedsProduct() {
    const product = this.createProduct();
    product.doThing();
  }
}

class MyProduct {
  doThing() {
    console.log("Does a thing.")
  }
}

class MyCreator {
  // Determines which abstract product to create
  createProduct() {
    return new MyProduct()
  }
}
RSS icon github logo linkedin logo

Zachary W. Huang © 2021-2024