观察者模式 + Kotlin 泛型实现的简易版消息中心
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| class MessageCenter<T> { companion object { private val centers = mutableMapOf<String, Any>() fun <T> getInstance(clazz: Class<T>): MessageCenter<T> { return if (centers[clazz.simpleName] != null) { centers[clazz.simpleName] as MessageCenter<T> } else { val messageCenter = MessageCenter<T>() centers[clazz.simpleName] = messageCenter messageCenter } } }
fun register(observer: Observer<T>) { observers.add(observer) }
fun unregister(observer: Observer<T>) { if (observers.contains(observer)) { observers.remove(observer) } }
fun post(t: T) { observers.forEach { it.receive(t) } }
private var observers = mutableListOf<Observer<T>>() }
interface Observer<T> { fun receive(t: T) }
fun main() { val ob = object : Observer<String> { override fun receive(t: String) { println("result is: $t") } } MessageCenter.getInstance(String::class.java).register(ob) MessageCenter.getInstance(String::class.java).post("txt post.") MessageCenter.getInstance(String::class.java).unregister(ob)
MessageCenter.getInstance(Int::class.java).post(123) }
|