如何避免 class 中的代码重复?

How to avoid duplication of code in class?

我有两个 class 扩展抽象 class:

   class SubstitutionTeacher extends SubstitutionAbstract {
      abstract _save();
    }

    class SubstitutionFree extends SubstitutionAbstract {
      public _save() {
      }
    }

    class SubstitutionSubject extends SubstitutionAbstract {
      public _save() {
      }
    }

在方法save()中我实现了这样的行为:

  /* Class SubstitutionFree
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          subsDate: this.substitution.date,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }

 /* Class SubstitutionSubject
    public _save() {

        const substitutionAdd: ISubstitutionModelTeacher = {
          lesson: this.substitution.lessonNumber,
          confirmed: true,
          newTeacher: this.substitution.teacher
        };

        return this.replaceService.addSubstitution(substitutionAdd);
      }

如您所见,这两种方法几乎相似。我想避免这种重复:

{ lesson: this.substitution.lessonNumber,
confirmed: true,
newTeacher: this.substitution.teacher
}

我可以将 save() 更改为常规 save() 并传递一个公共部分,但它失去了抽象的意义。

这可能是无效的打字稿,只是因为我的打字稿不太好:)

但是您的问题不是特定于 typescript 的,因此也许这会让您了解如何解决此类问题。

SubstitutionAbstract 中创建一个方法:

class SubstitutionAbstract {

    // this one should be called each time you need that object instead of duplicating
    // you can make it protected if there is such stuff in typescript
    public getMyStuff(param1, param2, param3, param4) {
        return { lesson: param1,
                 confirmed: param2,
                 newTeacher: param3,
                 subsDate: param4
               };
    }  
    // .....
}

在你的每个子类中调用它:

public _save() {
    const substitutionAdd: ISubstitutionModelTeacher = 
             getMyStuff(this.substitution.lessonNumber, true, 
                           this.substitution.date, this.substitution.teacher);

    return this.replaceService.addSubstitution(substitutionAdd);
}

如果您在某些实现中不需要 subsDate,则将 null 传递给 getMyStuff,不要认为这可能是个问题。 Typescript 可能会检查类型等,因此您可能需要使用该方法才能工作(例如,我猜它应该 return 类型 ISubstitutionModelTeacher 的东西)。

再一次 - 这可能是无效代码,因为打字稿不是我的领域,但它描述了你如何做的想法。

当然还有其他方法,这只是 1 个示例。

快乐编码:)