Skip to content

Instantly share code, notes, and snippets.

@htdangkhoa
Last active April 21, 2022 06:54
Show Gist options
  • Save htdangkhoa/92f4f6efddad4a25b8244059476ccd92 to your computer and use it in GitHub Desktop.
Save htdangkhoa/92f4f6efddad4a25b8244059476ccd92 to your computer and use it in GitHub Desktop.
Abstract Factory Pattern in Typescript
export interface AbstractFactory {
createProductA(): AbstractProductA;
createProductB(): AbstractProductB;
}
class ConcreteFactory1 implements AbstractFactory {
public createProductA(): AbstractProductA {
return new ConcreteProductA1();
}
public createProductB(): AbstractProductB {
return new ConcreteProductB1();
}
}
class ConcreteFactory2 implements AbstractFactory {
public createProductA(): AbstractProductA {
return new ConcreteProductA2();
}
public createProductB(): AbstractProductB {
return new ConcreteProductB2();
}
}
export interface AbstractProductA {
usefulFunctionA(): string;
}
export class ConcreteProductA1 implements AbstractProductA {
public usefulFunctionA(): string {
return "The result of the product A1.";
}
}
export class ConcreteProductA2 implements AbstractProductA {
public usefulFunctionA(): string {
return "The result of the product A2.";
}
}
export interface AbstractProductB {
usefulFunctionB(): string;
}
export class ConcreteProductB1 implements AbstractProductB {
public usefulFunctionB(): string {
return "The result of the product B1.";
}
}
export class ConcreteProductB2 implements AbstractProductB {
public usefulFunctionB(): string {
return "The result of the product B2.";
}
}
import { AbstractFactory } from './AbstractFactory';
import { ConcreteFactory1, ConcreteFactory2 } from './ConcreteFactory'
function clientCode(factory: AbstractFactory) {
const productA = factory.createProductA();
const productB = factory.createProductB();
console.log(productA.usefulFunctionA());
console.log(productB.usefulFunctionB());
}
console.log("Client: Testing client code with ConcreteFactory1");
clientCode(new ConcreteFactory1());
console.log("----------------");
console.log("Client: Testing the same client code with ConcreteFactory2");
clientCode(new ConcreteFactory2());
/*
Output:
Client: Testing client code with ConcreteFactory1
The result of the product A1.
The result of the product B1.
----------------
Client: Testing the same client code with ConcreteFactory2
The result of the product A2.
The result of the product B2.
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment