Skip to content

Instantly share code, notes, and snippets.

@rajikaimal
Last active February 8, 2019 10:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rajikaimal/301ef4da3afe23776daa624e6034b9e8 to your computer and use it in GitHub Desktop.
Save rajikaimal/301ef4da3afe23776daa624e6034b9e8 to your computer and use it in GitHub Desktop.
Abstract factory in TypeScript
interface PorscheModel {
engine: string;
tyreModel: string;
gears: number;
}
class PorscheCar implements PorscheModel {
engine: string;
tyreModel: string;
gears: number;
constructor(params) {
this.engine = params.engine;
this.tyreModel = params.tyreModel;
this.gears = params.gears;
}
}
interface PorscheFactoryModel {
creatCar(param: PorscheModel);
}
interface Factory {
createCar(params: PorscheCar);
}
class PorscheCarFactory implements Factory {
createCar(params) {
return new PorscheCar(params);
}
}
interface FerrariModel extends PorscheModel {
turbo: boolean;
}
class FerrariCar implements FerrariModel {
engine: string;
tyreModel: string;
gears: number;
turbo: boolean;
constructor(params) {
this.engine = params.engine;
this.tyreModel = params.tyreModel;
this.gears = params.gears;
this.turbo = params.turbo;
}
}
class FerrariCarFactory implements Factory {
createCar(params) {
return new FerrariCar(params);
}
}
class CarFactoryImpl {
porscheCar: Factory;
ferrariCar: Factory;
constructor() {
this.porscheCar = new PorscheCarFactory();
this.ferrariCar = new FerrariCarFactory();
}
getPorsche() {
return this.porscheCar;
}
getFerrari() {
return this.ferrariCar;
}
}
const fact = new CarFactoryImpl();
let porscheParams = { engine: "raw", tyreModel: "basic", gears: 1 };
const concretePorsche = fact.getPorsche().createCar(porscheParams);
console.log(concretePorsche.engine);
let ferrariParams = { engine: "rawraw", tyreModel: "basic", gears: 2, turbo: true };
const concreteFerrari = fact.getFerrari().createCar(ferrariParams);
console.log(concreteFerrari.turbo);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment