mercredi 18 mai 2016

Design pattern with delegate being used by multiple class

I want to send data from a class to other classes via delegation method. However i found a problem at which for each class which needs to listen to the data changes, i would have to create a separate delegate protocol for them.

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)")
  }

}

The above code is a over simplified version of what i meant.

Of course by

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

or

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

is possible to be one of the solution but

i want to write this very particularly using the delegation method

If it is possible, is there anyway i can achieve this without a separate protocol for each class?

Aucun commentaire:

Enregistrer un commentaire