设计模式之观察者模式
Posted super码王
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了设计模式之观察者模式相关的知识,希望对你有一定的参考价值。
案例展示
原理分析
代码实现
- Observer 接口
//观察者接口,由观察者来实现
interface Observer
fun update(temperatrue: Float?, pressure: Float?, humidity: Float?)
-
Observer 接口的实现
class CurrentConditions : Observer
var temperatrue: Float? = null
var pressure: Float? = null
var humidity: Float? = null
override fun update(temperatrue: Float?, pressure: Float?, humidity: Float?)
this.temperatrue = temperatrue
this.pressure = pressure
this.humidity = humidity
display()
fun display()
println("Temperatrue: $temperatrue , Pressure: $pressure , Humidity: $humidity")
-
Subject 接口
interface Subject
fun registerObserver(o: Observer)
fun removeObserver(o: Observer)
fun notifyObservers()
- Subject 接口的实现
class WeatherData : Subject
var temperatrue: Float? = null
var pressure: Float? = null
var humidity: Float? = null
val observers: MutableList<Observer> = ArrayList()
override fun registerObserver(o: Observer)
if (!observers.contains(o))
observers.add(o)
override fun removeObserver(o: Observer)
if (observers.contains(o))
observers.remove(o)
override fun notifyObservers()
observers.forEach
it.update(temperatrue, pressure, humidity)
fun setData(temperatrue: Float?, pressure: Float?, humidity: Float?)
this.temperatrue = temperatrue
this.pressure = pressure
this.humidity = humidity
notifyObservers()
- 调用代码
fun main()
val currentConditions = CurrentConditions()
val weatherData = WeatherData()
weatherData.registerObserver(currentConditions)
weatherData.setData(10F, 20F, 30F)
- 效果展示
以上是关于设计模式之观察者模式的主要内容,如果未能解决你的问题,请参考以下文章