目录

行为型:中介者模式

释义

中介者模式,在通信的两者间,增加一个中介类去处理通信问题,我们在通信时只需要维护中介类即可。

/%E8%A1%8C%E4%B8%BA%E5%9E%8B%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F/%E8%A1%8C%E4%B8%BA%E5%9E%8B%EF%BC%9A%E4%B8%AD%E4%BB%8B%E8%80%85%E6%A8%A1%E5%BC%8F.resources/55EEB735-5652-4FEE-BEC1-497660DD0F16.png
中介者模式

信源Source通过sendMessage发出的消息,通过调用中介类MeduimshowMessage()进行发送。

中介类

1
2
3
4
5
6
7
class Medium {
    companion object {
        fun showMessage(msg: String) {
            toShowMessage()
        }
    }
}

信源

1
2
3
4
5
6
class Source {
    fun sendMessage(msg: String) {
        // 调用中介类的方法完成通信
        Medium.showMessage(msg)
    }
}

使用

1
2
3
4
5
fun main() {
    val source: Source = Source()
    // 方法中会调用中介类的方法完成通信
    source.sendMessage("Message")
}