typescript - 如何使用 OOP 改进解决方案?
问题描述
Car
如果有两种类型Big
,我有一个实体Small
。
我的 HTML 页面包含两个表单。根据所选表格,我知道 type: Big
, Small
.
我的打字稿看起来像:
public type: "Big" | "Small";
public CarSmall: Car;
public CarBig: Car;
提交表单后,我调用函数:
public save(): void {
if (this.type == "Big") {
const bigCarProperties = {}; // Get data specialized for this type
save(bigCarProperties) ;
}
if (this.type == "Small") {
const smallCarProperties = {}; // Get data specialized for this type
save(smallCarProperties);
}
}
wheresave()
函数接受不同数量的参数。
所以,我不喜欢这种方法,如何在 TypeScript 中使用 OOP 来改进它?
当然,我可以创建两个使用方法扩展父类 Car 的类,Save();
但是方法Save()
不是 Car 的属性,它是另一个责任区域。
我不需要关心结果输出对象汽车,无论哪种类型,我只需要保存它。
解决方案
并不是说您在保存方法中调用保存,我只是将与获取汽车属性相关的逻辑移动到另一个函数,在您的代码中,小型和大型汽车都是 Car 类即时,因此保存方法应该适用于两个对象
getCarProperties(type:string) {
if (this.type == "Big") {
return bigCarProperties = {};
} else {
return smallCarProperties = {};
}
}
public send(): void {
this.save(this.getCarProperties(this.type));
}
public save(car:Car) : void {
....
}