Using Swift to write an observer pattern, a collection of swift language classes, arrays, protocols, methods, strings, conditional control statements and some other syntax.
A brief introduction to the observer pattern, in the observer pattern, would change the state of the subject and the number of observers. With this pattern, you can change the objects that depend on the subject state, without having to change the theme.
//main.swift //Observer(观察者模式) //Created by jy on 15/4/26. //Copyright (c) 2015年 jy. All rights reserved. import Foundation //观察者模式中,会改变的是主题的状态以及观察者的数目。用这个模式,可以改变依赖于主题状态的对象,去不必改变主题。 //主题和观察者都使用协议:观察者利用主题的协议向主题注册,而主题利用观察者协议(接口)通知观察者。这样可以让两者运作正常,又同时具有松耦合的特点 //定义协议,观察者要实现的 protocol Observerable{ func update(); } //观察者实现协议 class Subscriber : Observerable{ //定义属性状态 func update() { println( "Callback" ) } } /** * 主题 */ class Paper{ //定义空数组 var observers = Array<Subscriber>() //注册观察者 func register(sub:Subscriber){ self.observers.append(sub) } //外部统一访问 func trigger(){ var count = self.observers. count ; //判断是否注册为空 if count != 0 { for obs in self.observers { //通知 obs.update() } } } } var paper = Paper() //观察者 var sub1 = Subscriber() var sub2 = Subscriber() //注册 paper.register(sub1) paper.register(sub2) paper.trigger() |
Swift Observer mode