我有两个类扩展了抽象类:
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(),并将其传递到其中的一个公共部分,但它失去了抽象的意义。
发布于 2018-04-04 16:32:10
这可能是无效的打字稿,仅仅是因为我在打字稿方面没有那么好:)
但是您的问题并不是特定类型的,所以这可能会给您一个如何解决这些问题的想法。
在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,不要认为这是一个问题。类型记录可能会检查类型等,因此您可能需要使用该方法来工作(例如,它应该返回ISubstitutionModelTeacher类型的东西,我猜)。
再说一遍--这可能是不工作的代码,因为类型记录不是我的领域,但是它描述了您可以做什么的想法。
当然还有其他的方法,这只是一个例子。
快乐编码:)
https://stackoverflow.com/questions/49655777
复制相似问题