我有两个扩展抽象类的类:
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()
并向其传递公共(public)部分,但它失去了抽象的意义。
最佳答案
这可能是无效的 typescript,只是因为我的 typescript 不是很好 :)
但是您的问题不是特定于 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 可能会检查类型等,因此您可能需要使用该方法才能工作(例如,我猜它应该返回 ISubstitutionModelTeacher
类型的东西)。
再一次 - 这可能不是工作代码,因为 typescript 不是我的领域,但它描述了你如何做的想法。
当然还有其他方法,这只是 1 个示例。
快乐编码:)
关于typescript - 如何避免类中的代码重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49655777/