Skip to content

Instantly share code, notes, and snippets.

@embarq
Created February 7, 2018 12:08
Show Gist options
  • Select an option

  • Save embarq/a457070b686e587fd7f0bd0f3bd381f0 to your computer and use it in GitHub Desktop.

Select an option

Save embarq/a457070b686e587fd7f0bd0f3bd381f0 to your computer and use it in GitHub Desktop.
class DIContainer {
diMap: {
[key: string]: any
}
initialDiMap: {
[key: string]: any;
}
add(_class) {
this.initialDiMap[_class.name] = _class;
}
get(className) {
return this.diMap[className];
}
bootstrap() {
for (let className in this.diMap) {
this.diMap[className] = new this.initialDiMap[className];
}
}
}
interface Engine {
label: string;
}
class OilEngine implements Engine {
public label: string;
constrcutor() {
this.label = 'V8';
}
}
class ElectricEngine implements Engine {
public label: string;
constrcutor() {
this.label = 'Tesla';
}
}
class SunEngine {
}
interface CarBody {
type: string;
}
class SedanBody implements CarBody {
public type: string;
constructor() {
this.type = 'Sedan';
}
}
class Car {
public engine: Engine;
public body: CarBody;
static inject = ['ElectricEngine', 'SedanBody'];
constructor(engine: Engine, body: CarBody) {
this.engine = engine || null;
this.body = body || null;
}
}
class App {
constructor() {
const di = new DIContainer();
di.add(ElectricEngine);
di.add(SedanBody);
di.bootstrap();
const electricCar = new Car(di.get(Car.inject[0]), di.get(Car.inject[1]))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment