【发布时间】:2018-11-23 22:06:33
【问题描述】:
如果有两种类型Big、Small,我有一个实体Car。
我的 HTML 页面包含两个表单。根据所选表格,我知道类型:Big、Small。
我的 TypeScript 看起来像:
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);
}
}
其中save() 函数接受不同数量的参数。
所以,我不喜欢这种方法,如何在 TypeScript 中使用 OOP 来改进它?
当然,我可以创建两个类来扩展父类 Car 使用方法 Save(); 但方法 Save() 它不是 Car 的属性,它是另一个责任区域。
我不需要关心结果输出对象汽车,无论哪种类型,我只需要保存它。
【问题讨论】:
-
我可以应用工厂模式来创建具体类的特定对象
标签: typescript oop