インジェクションの依存関係の問題に取り組んでいます。ここで、デリゲート パターンの場合にインターフェイス分離の原則をどのように使用するかという疑問が生じます。依存性注入に Swinject フレームワークを使用しています。どうすればこれを解決できますか?
class Client {
private var interface: ParentInterface
...
func execute() {
interface = globalContainer.resolve(ParentInterface.self)
interface?.parentMethod()
}
}
protocol ParentInterface {
func parentMethod()
}
class Parent: ParentInterface, ParentDelegate {
// Dependency
private var child: Child? // I WANT TO USE AN PROTOCOL HERE, NOT THE CLASS
init(childReference: Child) {
self.child = childReference
self.child?.delegate = self // But if I use the protocol I cant access the delegate property
}
public func parentMethod() {
let result = calcSomething()
// Access child class interface method
child?.childMethod(result)
}
...
}
子クラス、これまでのところ異常はありません。
protocol ParentDelegate: class {
func delagteMethod(value: Double)
}
protocol ChildInterface {
func childMethod(_ result: Double)
}
class Child: ChildInterface {
weak var delegate: ParentDelegate?
...
private func delagteMethod() {
delegate?.delagteMethod(value: someValue)
}
}
しかし、依存関係を適切に注入するには、直接のクラス参照ではなく、プロトコルが必要ですよね? このような:
// Would like to
container.register(ParentInterface.self) { r in
Parent(childInterface: r.resolve(ChildInterface.self)!)
}
// Only way I get it working without interface
container.register(ParentDelegate.self) { r in
Parent(childClass: Child())
}
container.register(ChildInterface.self) { _ in Child() }
.initCompleted { r, c in
let child = c as! Child
child.delegate = r.resolve(ParentDelegate.self)
}
要するに、ぐるぐる回っています。子クラスのインターフェイスを使用すると、デリゲート プロパティにアクセスできません。クラス参照を使用すると、インターフェイス メソッドをモック/スタブすることはできません。
私は何が欠けていますか?よろしくお願いします!