1:主类
package design
/**
* Created by czq on 2018/12/9.
*/
class Obsever {
var callbacklist: List[EventCallBack] = Nil
def registerEventCallback(callback: EventCallBack): Unit = {
if (!find(callback)) {
//把callback注册进去
callbacklist = callbacklist.::(callback)
println(callbacklist)
}
}
def find(callback: EventCallBack): Boolean = {
if (callbacklist.contains(callback)) {
return true
}
else{
return false
}
}
def sendEvent(id: Int, data: String): Unit ={
dispatch(id, data)
}
def dispatch(id: Int, data: String): Unit = {
for (elem <- callbacklist) {
if (elem.checkEventId(id)) {
elem.onEvent(id, data);
}
}
}
}
object Obsever{
def main(args: Array[String]) {
val test = new EventCallBackTest
val list = List(1,2,3,4,5)
test.registerEventList(list)
val obs = new Obsever
obs.registerEventCallback(test)
obs.sendEvent(1, "sss")
obs.sendEvent(2, "abc")
obs.sendEvent(3, "efg")
obs.sendEvent(4, "lmn")
}
}
2:事件接口
package design
import scala.util.control.Breaks._
/**
* Created by czq on 2018/12/9.
*/
trait EventCallBack {
var list: List[Int] = List()
def registerEventList(list0: List[Int]){
list = list0
}
def onEvent(evId: Int, buf: String) : Unit
def checkEventId(evId: Int): Boolean = {
var ret = false
breakable {
for (elm <- list) {
if (elm == evId) {
ret = true
break
}
}
}
return ret
}
}
3:测试类
package design
/**
* Created by czq on 2018/12/10.
*/
class EventCallBackTest extends EventCallBack {
def onEvent(evId: Int, buf: String) : Unit = {
printf("id = %d, buf = %s\n", evId, buf)
}
}
4:测试结果
List(design.EventCallBackTest@8998537)
id = 1, buf = sss
id = 2, buf = abc
id = 3, buf = efg
id = 4, buf = lmn