Factory method pattern - DeanHristov/ts-design-patterns-cheat-sheet GitHub Wiki
A Factory Method is a creational design pattern that provides an interface for creating objects in a superclass but allows subclasses to alter the type of objects that will be created. A simple UML diagram can be seen here.
A Great fit when:
- When we don’t know beforehand the exact types and dependencies of the objects with which the code should work.
- When we want to save resources by reusing existing objects instead of rebuilding them each time.
Example:
Public contract
// Product type
interface IBurger {
burgerName: string;
}
The creator class
abstract class ChefCreator {
cookBurger() {
return this.factoryMethod();
}
protected abstract factoryMethod(): Burger;
}
A concrete creator 1
class AmericanChef extends ChefCreator {
protected factoryMethod(): IBurger {
return new BeefBurger('BeefBurger');
}
}
A concrete creator 2
class ItalyChef extends ChefCreator {
protected factoryMethod(): IBurger {
return new VeggieBurger('VeggieBurger');
}
}
A concrete product 1
class BeefBurger implements IBurger {
burgerName: string;
constructor(burgerName: string) {
this.burgerName = burgerName;
}
}
A concrete product 2
class VeggieBurger implements IBurger {
burgerName: string;
constructor(burgerName: string) {
this.burgerName = burgerName;
}
}
Code in action
const italyChef: ItalyChef = new ItalyChef();
const americanChef: AmericanChef = new AmericanChef();
const veggieBurger: IBurger = italyChef.cookBurger();
const beefBurger: IBurger = americanChef.cookBurger();
console.log(beefBurger); // { burgerName: 'BeefBurger' }
console.log(veggieBurger); // { burgerName: 'VeggieBurger' }
More info can be found on the wiki page.