按照Hevery的建议,将合作者注入构造函数而不是构造函数体内的新东西,当协作者需要对其所有者进行反向引用时,如何优雅地这样做,而不使用邪恶的'init‘方法(这又违反了Hevery的可测试代码的最佳实践)。
例如。
export class Model {
constructor( history ) {
this._history = history; // But history needs to know Model too
history.model = this; // Is it just as simple as this? Feels awkward
...
}
...
}与
export class Model {
constructor() {
this._history = new History(this); // But new'ing things here reduces testability
...
}
...
}发布于 2018-03-23 22:54:09
我认为这是一个只需要在构造函数中创建实例( new up)的例子。如果这两件事没有对方就不能存在,而且不需要使用多态性,那么传递依赖关系是没有意义的。
否则,需要打破模型和历史之间的循环依赖关系。
发布于 2018-03-23 23:24:17
您可以注入一个工厂而不是一个实例:
export class Model {
constructor(HistoryFactory factory) {
this._history = factory.createHistory(this);
...
}
...
}但我想米斯科会建议你摆脱循环依赖。
https://softwareengineering.stackexchange.com/questions/368237
复制相似问题