1. 程式人生 > >【Lua】觀察者模式在Lua中的實現

【Lua】觀察者模式在Lua中的實現

--LUA對於觀察者模式的實現

--被觀察者表
Subject = {}
--類似父類,具體對於lua面向物件程式設計思想學習看這裡:
--http://www.jb51.net/article/55724.htm
function Subject:new(obj)
	obj = obj or {}
	setmetatable(obj, self)  --例項化物件指向Subject,這樣就以Subject為模版了
	--將Father的__index欄位指向自己,以便新物件在找不到指定的key時可以被重定向,即訪問Father擁有的key
	self.__index = self
end

CreateSubject = Subject:new()
--註冊
function CreateSubject:Add(obs)
	if self.observers == nil then
		self.observers = {}
	end
	table.insert(self.observers,obs)
end
--登出
function CreateSubject:Del(obs)
	for k, v in pairs(self.observers) do
		if v == obs then
			table.remove(self.observers,k)
			break
		end
	end
end

function ConcreteSubject:Notify()
	for _, v in pairs(self.observers) do
		v:Update()
	end
end

Observe = {}

function Observer:new(obj)
	obj = obj or {}
	setmetatable(obj,self)
	self.__index = self
	return o
end

CreateObserver = Observer:new()

function CreateObserver:new(s,n)
	obj = {}
	setmetatable(obj,self)
	self.__index = self
	obj.subject = s
	obj.observername = n
	return obj
end

function CreateObserver:Update()
 print(self.observername.."!!"..self.subject.subjectstate)
end

s = CreateSubject:Update()

xiyangyang = CreateObserve:new(s,"喜羊羊")
meiyangyang = CreateObserve:new(s,"美羊羊")
lanyangyang = CreateObserve:new(s,"懶羊羊")

s:Add(xiyangyang)
s:Add(meiyangyang)
s:Add(lanyangyang)

s.subjectstate = "灰太狼來了快躲起來!"
s.Notify()

s:Del(lanyangyang)

s.subjectstate = "灰太狼走了出來吧!"

s:Notify()