委托被多个 class 使用的设计模式

Design pattern with delegate being used by multiple class

我想通过委托方法将数据从 class 发送到其他 classes。但是我发现了一个问题,对于每个需要监听数据变化的class,我必须为它们创建一个单独的委托协议。

protocol MainDelegateForA {
  func mainResultObtained(result: String)
}

protocol MainDelegateForB {
  func mainResultObtained(result: String)
}

class MainViewController: UIViewController {

  var delegateForA: MainDelegateForA?
  var delegateForB: MainDelegateForB?

  override func viewDidLoad() {
    let subscribingViewA = SubscribingViewA()
    delegateForA = subscribingViewA
    let subscribingViewB = SubscribingViewB()
    delegateForB = subscribingViewB
    distributeResult("Calculation obtained!!!")
  }

  func distributeResult(result: String) {
    delegateForA?.mainResultObtained(result)
    delegateForB?.mainResultObtained(result)
  }

}

class SubscribingViewA: MainDelegateForA {

  func mainResultObtained(result: String) {
    print("SubscribingViewA got result:\(result)")
  }

}

class SubscribingViewB: MainDelegateForB {

  func mainResultObtained(result: String) {
    print("SubscribingViewA got result:\(result)")
  }

}

以上代码是我的意思的过度简化版本。

当然是

keeping a reference of each class and send the result via directly calling a public method of the class

Using notification and make every class that needs the changes to listen to the data change

可能是解决方案之一,但

i want to write this very particularly using the delegation method

如果可能的话,我是否可以在不为每个 class 单独的协议的情况下实现这一目标?

您可以使用一些模式。

1) 您可以允许多个侦听器,并让他们以与目标操作的工作方式大致相同的方式注册。您的 class 将遍历侦听器数组并调用适当的方法。

2) 您可以改用通知。

我倾向于第一种方法,因为它提供了更多的编程安全性。

正如 luk2302 所指出的,您可以使用委托数组来实现它:

var delegates = [MainDelegate]()

那么你只需要使用一个循环(也许在swift中可以简化):

for delegate in self.delegates {
    delegate.mainResultObtained(result)
}