我有一个问题(接口(interface)
)的数组
,我需要根据问题类型将其发送到许多函数之一。我认为我的一系列 if
语句非常丑陋,我希望有一种遵循 SOLID 的方法来做到这一点。我相信我违反了 O(开放扩展,关闭修改)。
renderQuestionList(contents: Question[]): HTMLElement {
return yo`
<div>${contents.map(q => {
if (q.type == 'passfailna') { return this.renderQuestionPassfailna(q) };
if (q.type == 'yesno') { return this.renderQuestionYesno(q) };
if (q.type == 'numeric') { return this.renderQustionNumeric(q) };
})}
</div>`;
}
那么,
renderQuestionPassfailna(q: Question): any {
return yo`<div>Stuff</div>`;
}
renderQuestionYesno(q: Question): any {
return yo`<div>Other Stuff</div>`;
}
renderQustionNumeric(q: Question): any {
return yo`<div>I'm Helping!</div>`;
}
最佳答案
太丑了。构建功能图怎么样?也许类似
constructor() {
this.questions = {
passfailna: q => this.renderQuestionPassfailna(q),
yesno: q => this.renderQuestionYesno(q),
numeric: q => return this.renderQustionNumeric(q)
};
}
renderQuestionList(contents: Question[]): HTMLElement {
return yo`<div>${contents.map(q => this.questions[q.type](q))}</div>`;
}
关于JavaScript/TypeScript Array interface[] ,按类型分组以发送多个函数中的 1 个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52026818/