Swift中的观察者模式

我想实现一个观察者模式,但是我没有在Swift(也是2.0)中找到正确的编程语言结构。主要问题是:

I want to implement an observer pattern, but I do not find the proper programming language constructs in Swift (also 2.0). The main problems are:


  1. protocol extension 不允许存储的属性。

  2. 在类中,我们可以添加存储的属性,但是我们不能强制子类覆盖它的一些继承方法。

  1. protocol and extension does not allow stored properties.
  2. In classes we could add stored properties, but we can not force a subclass to override some of its inherited methods.

这就是我想要的:

{class|protocol|extension|whathaveyou} Sensor {
    var observers = Array<Any>() // This is not possible in protocol and extensions 
    // The following is does not work in classes
    func switchOn() 
    func switchOff()
    var isRunning : Bool {
        get
    }
}

class LightSensor : Sensor {
    //...
    override func switchOn() {
        // turn the sensor on
    }
}

// In the class C, implementing the protocol 'ObserverProtocol'

var lightSensor = LightSensor()
lightSensor.switchOn()
lightSensor.registerObserver(self) // This is what I want

以下是我的知识:

class Sensor {
    private var observers = Array<Observer>()

    func registerObserver(observer:ObserverDelegate) {
        observers.append(observer)
    }
}

protocol SensorProtocol {
    func switchOn()
    func switchOff()
    var isRunning : Bool {
        get
    }
}

class LightSensor : Sensor, SensorProtocol {
    func switchOn() {
        //
    }
    func switchOff() {
        //
    }

    var isRunning : Bool {
        get {
            return // whatever
        }
    }
}

但这不是很方便,因为传感器 SensorProtocol 应该齐头并进,并且要求子类 LightSensor 必须满足。

But this is not very convenient, because both Sensor and SensorProtocol should come hand in hand, and are both requirements the subclass LightSensor has to fulfill.

任何想法?



 1 条回答