typescript builder design pattern using literal class name
npm install typescript-buildercompile typescript:
npm run tsc
node index
typescript based builder example.
Typescript builder pattern and example.
```
yarn add typescript-builder
export class AnimalBuilder extends Builder { constructor(type: any) {
super(type) ;
}
setType(type: string): AnimalBuilder {
let inst = this.getInstance() ;
inst.Type = (type || "animal");
return this;
}
setkingdom(kingdom: string): AnimalBuilder {
this.getInstance().Kingdom = kingdom;
return this;
}
setSound(sound: string): AnimalBuilder {
this.getInstance().Sound = sound;
return this;
}
}
export abstract class Animal {
private type: string;
private kingdom: string;
private sound: string;
set Type(type: string) { this.type = type };
get Type() { return this.type; };
set Sound(sound: string) { this.sound = sound };
get Sound() { return this.sound; };
set Kingdom(kingdom: string) { this.kingdom = kingdom };
get Kingdom() { return this.kingdom; };
constructor() {
this.type = "" ;
this.kingdom = "animal" ;
this.sound = "" ;
}
}
export class Dog extends Animal {
public Bark() {
return this.Sound ;
}
constructor() {
super() ;
}
}
export class Cat extends Animal {
public Miau() {
return this.Sound ;
}
constructor() {
super() ;
this.Kingdom = "pet" ;
}
}
const animalBuilder = new AnimalBuilder(Dog);
animalBuilder.setType("dog").setSound("bark");
let dog = animalBuilder.getInstance();
console.log("dog", dog, dog.Bark());
const animalBuilder2 = new AnimalBuilder(Cat);
let cat = animalBuilder2.getInstance();
animalBuilder2.setType("cat").setSound("miau");
console.log("cat", cat, cat.Miau());
``This project is licensed under the MIT License - see the LICENSE file for details