Zachary W. Huang
Idea: Define an abstract “Factory” class which generates products. We can alter every product by simply changing which factory is used.
Example: Using an abstract factory to generate differently-themed GUI widgets - switch styles by simply changing the concrete factory used.
interface ProductOne {}
interface ProductTwo {}
abstract class Factory {
abstract makeProductOne(): ProductOne;
abstract makeProductTwo(): ProductTwo;
}
class FactoryA extends Factory {
makeProductOne() {
return { contents: 1, style: "A" }
}
makeProductTwo() {
return { contents: 2, style: "A" }
}
}
class FactoryB extends Factory {
makeProductOne() {
return { contents: 1, style: "B" }
}
makeProductTwo() {
return { contents: 2, style: "B" }
}
}
function main(factory: Factory) {
const factory = new FactoryA();
const thing1 = factory.makeProductOne();
const thing2 = factory.makeProductTwo();
console.log(thing1.style, thing2.style); // "A A"
}