Created
August 15, 2018 17:42
-
-
Save karol-majewski/6bad10275bc561d57a57c42041bc819b to your computer and use it in GitHub Desktop.
Builder pattern example ported to TypeScript. See https://rafalstepien.com/zbyt-duza-liczba-parametrow-konstruktorze-wzorzec-projektowy-budowniczy-builder/
This file contains hidden or 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
enum PokemonType { | |
Water, | |
Rock, | |
Fire, | |
Air, | |
Electric, | |
Poison | |
} | |
class Pokemon { | |
private name?: string; | |
private color?: string; | |
private age?: number; | |
private type?: PokemonType; | |
private level?: number; | |
constructor(builder: Pokemon.Builder) { | |
this.name = builder.name; | |
this.color = builder.color; | |
this.age = builder.age; | |
this.type = builder.type; | |
this.level = builder.level; | |
} | |
} | |
namespace Pokemon { | |
/** | |
* To do: merge namespace with Pokemon. | |
* To do: spread arguments in constructor. | |
* To do: optionality. | |
*/ | |
export class Builder { | |
public name?: string; | |
public color?: string; | |
public age?: number; | |
public type?: PokemonType; | |
public level?: number; | |
public withName(name: string) { | |
this.name = name; | |
return this; | |
} | |
public withColor(color: string) { | |
this.color = color; | |
return this; | |
} | |
public withAge(age: number) { | |
this.age = age; | |
return this; | |
} | |
public hasType(type: PokemonType) { | |
this.type = type; | |
return this; | |
} | |
public onLevel(level: number) { | |
this.level = level; | |
return this; | |
} | |
public build() { | |
return new Pokemon(this); | |
} | |
} | |
} | |
const pikachu: Pokemon = new Pokemon.Builder() | |
.withName('Bob') | |
.withColor('yellow') | |
.withAge(13) | |
.hasType(PokemonType.Electric) | |
.onLevel(15) | |
.build(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See the improved version: https://gist.github.com/karol-majewski/1d2aee6b25892c7285555fda31327ba8