KotlinJava设计模式

观察者模式

2018-11-18  本文已影响2人  培枫

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 类用于对该模式的支持。

类图

class

Role

该模式一般包含以下角色

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)
}
class FeiWanGeConcreteSubject : WechatOfficialAccountsSubject() {
    override fun publish(msg: String?) {
        observers.forEach {
            it.update(msg)
        }
    }
}
interface DefaultObserver {
    fun getName(): String
    fun update(msg: String?)
}
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 觉得推送很烂,就不在订阅该公众号了。

以上

日更第七日

上一篇下一篇

猜你喜欢

热点阅读