【问题标题】:How to improve solution using OOP?如何使用 OOP 改进解决方案?
【发布时间】:2018-11-23 22:06:33
【问题描述】:

如果有两种类型BigSmall,我有一个实体Car

我的 HTML 页面包含两个表单。根据所选表格,我知道类型:BigSmall

我的 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


【解决方案1】:

不是您在保存方法中调用保存,我只是将与获取汽车属性相关的逻辑移动到另一个函数,在您的代码中,小型和大型汽车都是 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 {
 ....
}

【讨论】:

  • 你怎么看,它应该被OOP复杂化吗?
  • 所以,我想验证将是与 save() 相同的逻辑
  • 验证方法可以在getCarProperties之前运行,如果数据无效则无需保存,只需在执行任何操作之前检查即可
  • 如果您分享更多代码,我们可以提供更多解决方案
【解决方案2】:

如果你遵循使用ifswitch 语句来处理差异的模式,你最终会得到很多条件语句。

基本策略会将这些差异转移到一个类中,而不是测试属性或类型来分支逻辑。

interface Car {
    save(): void;
}

class SmallCar implements Car {
    protected hasTrolleyHandle: boolean = true;

    save() {
        console.log('Save small car properties.', JSON.stringify(this));
    }
}

class BigCar implements Car {
    protected hasBullBars: boolean = false;

    save() {
        console.log('Save big car properties.', JSON.stringify(this));
    }
}

// Examples
const smallCar = new SmallCar();
smallCar.save();

const bigCar = new BigCar();
bigCar.save();

// More examples
function saveCar(car: Car) {
    car.save();
}

saveCar(smallCar);
saveCar(bigCar);

因为我认为汽车不应该自救,所以存在轻微的单一责任违规行为 - 但不值得以这种规模解决问题。当事情变得更大时,您可能会受益于存储库和工厂。

您可以继续这种模式,以对大型和小型汽车进行不同的验证并处理其他差异。

如果大小卡片之间有很多相似之处,您可以创建一个基类,或委托给一个可以处理类似内容的类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-14
    • 1970-01-01
    相关资源
    最近更新 更多