Мне нравится этот шаблон компоновщика, который я нашел в сети, но в строгом режиме он не будет работать, потому что я получаю для первых 3 свойств ту же ошибку, что и для первого:
(property) PizzaBuilder.numberOfSlices: number
Property 'numberOfSlices' has no initializer and is not definitely assigned in the constructor.ts(2564)
export enum DoughType {
HEALTHY,
}
export enum Topping {
CHEESE,
}
export interface Pizza {
numberOfSlices: number;
isThin: boolean;
doughType: DoughType;
toppings: Topping[];
}
export class PizzaBuilder {
private numberOfSlices: number;
private isThin: boolean;
private doughType: DoughType;
private toppings: Topping[] = [];
public setNumberOfSlices(numberOfSlices: number): PizzaBuilder {
this.numberOfSlices = numberOfSlices;
return this;
}
public setIsThin(isThin: boolean): PizzaBuilder {
this.isThin = isThin;
return this;
}
public setDoughType(doughType: DoughType): PizzaBuilder {
this.doughType = doughType;
return this;
}
public addTopping(topping: Topping): PizzaBuilder {
this.toppings.push(topping);
return this;
}
public build(): Pizza {
if (this.isThin === undefined) this.isThin = false;
if (this.numberOfSlices === undefined) this.numberOfSlices = 8;
if (this.doughType === undefined) throw new Error('Dough type must be set');
if (this.toppings.length < 1) this.toppings.push(Topping.CHEESE);
return {
numberOfSlices: this.numberOfSlices,
isThin: this.isThin,
toppings: this.toppings,
doughType: this.doughType,
};
}
}
const pizza = new PizzaBuilder()
.setIsThin(true)
.setNumberOfSlices(6)
.setDoughType(DoughType.HEALTHY)
.addTopping(Topping.CHEESE)
.build();
Я хочу не указывать значения по умолчанию numberOfSlices
, isThin
и doughType
, так как кажется, что это противоречит идее строителя. Я не могу установить их на undefined
, так как это не сработает.
Есть ли решение, которое позволяет избежать чрезмерного вздутия? Добавление логических значений для определения того, было ли что-то установлено, похоже на ужасный кошмар.