我相信最简单的方法是使用单独的方法来设置isReady
值和没有静态方法的单个CarStatus
类:
class CarStatus {
private isReady: boolean;
constructor(private name: string, private color: string) {
this.name = name;
this.color = color;
}
public setReady() {
this.isReady = true;
}
public getStatus(): string {
let result = this.isReady ? 'is ready' : 'is not ready';
return `${this.color} ${name} ${result}.`;
}
}
let carStatus = new CarStatus("pride", "white");
carStatus.setReady();
console.log(carStatus.getStatus());
如果您认为每个概念都不是必需的或可以在不同时间设置,您也可以使用流利的方法。视情况而定,这可能是一种矫枉过正,举个例子:
class CarStatus {
constructor(private name: string, private color: string, private isReady: boolean) {
this.name = name;
this.color = color;
this.isReady = isReady;
}
public getStatus(): string {
let result = this.isReady ? 'is ready' : 'is not ready';
return `${this.color} ${name} ${result}.`;
}
}
class CarStatusBuilder {
private name: string;
private color: string;
private isReady: boolean;
public SetReady(): CarStatusBuilder {
return new CarStatusBuilder() { this.isReady = true};
}
public WithName(name: string): CarStatusBuilder {
this.name = name;
return this;
}
public WithColor(color: string): CarStatusBuilder {
this.color = color;
return this;
}
public Build(): CarStatus{
return new CarStatus(this.name, this.color, this.isReady);
}
}
let carStatus = new CarStatusBuilder()
.WithColor("white")
.WithName("pride")
.Build();
console.log(carStatus.getStatus());