我想实现一个观察者模式,但是我没有在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:
protocol
和 extension
不允许存储的属性。 protocol
and extension
does not allow stored properties. 这就是我想要的:
{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.
任何想法?