Abstract Factory
Posted by Dustin Boston in Design Patterns.
The Abstract Factory design pattern provides a way to create families of related objects without specifying their concrete classes. It ensures consistency among objects in a family and promotes flexibility when adding new variants or configurations.
Source Code Listing
code.ts
export abstract class AbstractProductA {
constructor(public argument: string) {
console.log(argument);
}
}
export abstract class AbstractProductB {
constructor(public argument: string) {
console.log(argument);
}
}
export class ConcreteProductA1 extends AbstractProductA {}
export class ConcreteProductA2 extends AbstractProductA {}
export class ConcreteProductB1 extends AbstractProductB {}
export class ConcreteProductB2 extends AbstractProductB {}
export abstract class AbstractFactory {
abstract createProductA(): AbstractProductA;
abstract createProductB(): AbstractProductB;
}
export class ConcreteFactory1 extends AbstractFactory {
createProductA(): AbstractProductA {
return new ConcreteProductA1("ConcreteProductA1");
}
createProductB(): AbstractProductB {
return new ConcreteProductB1("ConcreteProductB1");
}
}
export class ConcreteFactory2 extends AbstractFactory {
createProductA(): AbstractProductA {
return new ConcreteProductA2("ConcreteProductA2");
}
createProductB(): AbstractProductB {
return new ConcreteProductB2("ConcreteProductB2");
}
}
export class Client {
abstractProductA: AbstractProductA;
abstractProductB: AbstractProductB;
constructor(factory: AbstractFactory) {
this.abstractProductA = factory.createProductA();
this.abstractProductB = factory.createProductB();
}
}