如何在iOS中没有通知中心的情况下自行实现观察者模式?

时间:2018-12-26 17:05:21

标签: ios swift nsnotificationcenter

有人问了这个问题,但无法找到解决方案 没有通知中心,如何实现我自己的观察者模式?

1 个答案:

答案 0 :(得分:3)

我只会使用与NotificationCenter相同的基本模式。有一种添加和删除观察者的方法,以及一种在发生通知时告诉他们的方法。像这样:

class MyNotification {
    var notificationName: String
    init(name: String) {
        notificationName = name
    }
}

protocol MyObserver {
    func processNotification(notification: MyNotification);
}

class MyNotificationCenter {
    var observers : [MyObserver] = []

    func addObserver(observer: MyObserver) {
        // Add the observer to the array
    }

    func removeObserver(observer: MyObserver) {
        // Remove the observer from the array
    }

    func postNotification(notification: MyNotification) {
        // For each object in the observer array, call its processNotification() method
    }
}

请注意,这已简化。假定所有观察者都在监视所有通知。如果您想做一些更复杂的事情,那么您需要一个字典,将通知类型映射到观察者,并且仅通知正在观察特定通知的观察者。您可能还希望将更多数据放入notification中,以便observer可以做一些有用的事情。