Skip to content

Instantly share code, notes, and snippets.

@TCotton
Last active July 21, 2017 22:11
Show Gist options
  • Save TCotton/821afb63afef2ae4436bd4ede2cf7ce4 to your computer and use it in GitHub Desktop.
Save TCotton/821afb63afef2ae4436bd4ede2cf7ce4 to your computer and use it in GitHub Desktop.
builder pattern in TypeScript
interface BurgerBoy {
size: number;
cheese: boolean;
pepperoni: boolean;
lettuce: boolean;
tomato: boolean;
addPepperoni(): any;
addCheese(): any;
addLettuce(): any;
addTomato(): any;
build(): any;
}
type size = number;
type cheese = boolean;
type pepperoni = boolean;
type lettuce = boolean;
type tomato = boolean;
type extras = string;
class Burger {
private size: size;
private cheese: cheese = false;
private pepperoni: pepperoni = false;
private lettuce: lettuce = false;
private tomato: tomato = false;
constructor(builder) {
this.size = builder.size;
this.cheese = builder.cheese;
this.pepperoni = builder.pepperoni;
this.lettuce = builder.lettuce;
this.tomato = builder.tomato;
}
}
class BurgerBuilder implements BurgerBoy {
public size: size;
public extras: extras;
public cheese: cheese = false;
public pepperoni: pepperoni = false;
public lettuce: lettuce = false;
public tomato: tomato = false;
constructor(size: number) {
this.size = size;
}
public addPepperoni(): any {
this.pepperoni = true;
return this;
}
public addLettuce(): any {
this.lettuce = true;
return this;
}
public addCheese(): any {
this.cheese = true;
return this;
}
public addTomato(): any {
this.tomato = true;
return this;
}
public addExtras(extras: string[]): any {
this.extras = BurgerBuilder.createExtrasString(extras);
return this;
}
public build(): any {
return new Burger(this);
}
private static createExtrasString(extras: string[]): string {
return extras.join();
}
}
const newBurger = new BurgerBuilder(14).addPepperoni().addCheese().addLettuce().addTomato().addExtras(['onion', 'peppers']).build();
console.dir(newBurger);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment