Last active
February 8, 2019 10:36
-
-
Save rajikaimal/301ef4da3afe23776daa624e6034b9e8 to your computer and use it in GitHub Desktop.
Abstract factory in TypeScript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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