Observer pattern
The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods.
The observer pattern is also a key part in the familiar model–view–controller (MVC) architectural pattern.The observer pattern is implemented in numerous programming libraries and systems, including almost all GUI toolkits.
所谓观察者模式,23 种常用设计模式之一。java 中的事件处理模型,就是基于该模式的。用于定义对象间一对多的依赖关系,使得当一个对象状态发生改变时,其他相关以来对象都得到通知并更新。java 专门提供了Observable 类用于对该模式的支持。
类图
classRole
该模式一般包含以下角色
- Subject: 目标、主题,它持有一个被观察者的集合,提供 add/del 方法,同时定义 notify 方法用于通知观察者
abstract class WechatOfficialAccountsSubject {
protected val observers = mutableListOf<WechatObserver>()
fun addObs(observer: WechatObserver) {
observers.add(observer)
println("${observer.getName()} followed FeiWanGe.")
}
fun delObs(observer: WechatObserver) {
observers.remove(observer)
println("${observer.getName()} unfollowed FeiWanGe")
}
abstract fun publish(msg: String? = null)
}
- ConcreteSubject: 具体的被观察者对象。当该对象的状态发生改变时,会通知到各个观察者
class FeiWanGeConcreteSubject : WechatOfficialAccountsSubject() {
override fun publish(msg: String?) {
observers.forEach {
it.update(msg)
}
}
}
- Observer: 观察者, 一般为定义了 update 方法的接口类
interface DefaultObserver {
fun getName(): String
fun update(msg: String?)
}
- ConcreteServer: 具体观察者。
class WechatObserver(private val username: String) : DefaultObserver {
override fun getName(): String {
return this.username
}
override fun update(msg: String?) {
println("$username 已读推送 $msg")
}
}
代码场景微解析
fun main(args: Array<String>) {
val feiWanGe = FeiWanGeConcreteSubject()
val puck = WechatObserver("Puck")
val sTormSpirit = WechatObserver("STormSpirit")
val windRunner = WechatObserver("WindRunner")
feiWanGe.addObs(puck)
feiWanGe.addObs(sTormSpirit)
feiWanGe.addObs(windRunner)
feiWanGe.publish("Observer Pattern")
feiWanGe.delObs(sTormSpirit)
}
微信用户 Puck、STormSpirit 和 WindRunner 订阅了公众号非晚阁(貌似现在叫 非晚斋 了),之后非晚斋推送了一条更新《Observer Pattern》,各个订阅大哥都收到了该条推送,然后 STormSpirit 觉得推送很烂,就不在订阅该公众号了。
以上
日更第七日
网友评论