博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
实现一个事件观察者
阅读量:5862 次
发布时间:2019-06-19

本文共 2234 字,大约阅读时间需要 7 分钟。

--worldobserver.lua [[DESC:]]

--主题类
local subject = {}
subject.__index = subject
function subject:new()
local newsubject = {}
newsubject.topiclist = {}
newsubject.topicob = {}
setmetatable(newsubject,subject)
return newsubject
end
function subject:register(observer)
for k,ob in pairs(self.topicob) do
if ob ==observer then
return
end
end
table.insert(self.topicob,observer)
return true
end
function subject:unregister(observer)
for k,ob in pairs(self.topicob) do
if ob == observer then
self.topicob[k] = nil
return true
end
end
return false
end
function subject:update(topic,context)
self.topiclist[topic] = context
self:notifyobserver(topic,context)
end
function subject:notifyobserver(topic,context)
for _,ob in pairs(self.topicob) do
--notice observer who concern this topic
if ob.concern[topic] then
ob.recive(topic,context)
end
end
end
--观察者
local observer = {}
observer.__index = observer
function observer:new(concernlist,dealfunc)
local newobserver = {}
newobserver.concern = {}
for _,obtopic in pairs(concernlist) do
newobserver.concern[obtopic] = true
end
newobserver.recive = dealfunc
setmetatable(newobserver,observer)
return newobserver
end
weather = subject:new()
xiaohong = observer:new({"temp","sun","rain"},function (topic,context)
if topic == "temp" then
if context == -1 then
print("xiaohong: I think it's too cold!")
else
print("xiaohong: not bad today!")
end
end
if topic == "sun" then
print("xiaohong: sun is " .. context)
end
if topic == "rain" then
print("xiaohong: rain is " .. context )
end
end)
xiaolv = observer:new({"sun"},function (topic,context)
if context == -1 then
print("xiaolv: Is xiaohong hate cloudy?")
else
print("xiaolv: Sun! I love sun!")
end
end)
xiaolan = observer:new({"temp","rain"},function (topic,context)
if topic == "temp" then
if context == -1 then
print("xiaolan: Is xiaohong hate cold?")
else
print("xiaolan: It's warm today!")
end
end
if topic == "rain" then
if context == -1 then
print("xiaolan: Rain is romantic!")
else
print("xiaolan: It isn't rain today")
end
end
end)
weather:register(xiaohong)
weather:register(xiaolv)
weather:register(xiaolan)
--weather:update("temp",1)
--weather:update("sun",1)
weather:update("rain",1)

转载于:https://www.cnblogs.com/Fallever/p/6880698.html

你可能感兴趣的文章
DHCP报文类型
查看>>
网站***后安全处理
查看>>
儿童节,5岁宝宝写给程序员爸爸的一封信!萌翻了!
查看>>
在CentOS系统中把PHP 5.3.x更新到PHP 5.4.x
查看>>
JAVA poi操作EXCEL
查看>>
Android使用 startActivityForResult 、 onActivityResult 时的注意事项
查看>>
TortoiseGit TortoiseSVN不显示 图标状态 的解决办法和原因
查看>>
深刻理解Python中的元类(metaclass)
查看>>
计划任务 rsync 报错 :You have no controlling tty. Cannot read confirmation
查看>>
keepalived组播故障排查
查看>>
增加虚拟内存
查看>>
我的友情链接
查看>>
java web session management
查看>>
syslog Tips
查看>>
docker 存出,载入镜像
查看>>
Android - 设置带滚动条的TextView
查看>>
c语言:不用if,else语句,也不用循环条件等,输入一个字符,判断是否为大写字母...
查看>>
C++随笔(一)关于用int来表示一个对象指针并复原问题
查看>>
我的友情链接
查看>>
Ubuntu Linux下的QQ使用方案
查看>>