程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> 狀態模式lua實現

狀態模式lua實現

編輯:C#入門知識

--[[
	狀態模式(State Pattern)是設計模式的一種,屬於行為模式。
	適用場景:
	1.一個對象的行為取決於它的狀態,並且它必須在運行時刻根據狀態改變它的行為。
	2.一個操作中含有龐大的多分支結構,並且這些分支決定於對象的狀態。

]]--

Work = {}

function Work:new(o,s)
	o = o or {}
	setmetatable(o,self)
	self.__index = self
	o.hour = 0
	o.currentstate = s
	return o;
end

function Work:SetTime(h)
	self.hour = h
end

function Work:GetTime()
	return self.hour
end

function Work:SetState(s)
	self.currentstate = s
end

function Work:WriteProgram()
	self.currentstate:WriteProgram(self)
end

State = {}

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

MorningState = State:new()

function MorningState:WriteProgram(w)
	if w.hour < 12 and w.hour >= 9 then
		print("早上寫代碼,精神百倍")
	else
		w:SetState(NoonState:new())
		w:WriteProgram()
	end
end

NoonState = State:new()

function NoonState:WriteProgram(w)
	if w.hour < 14 and w.hour >= 12 then
		print("中午寫代碼,犯困了,先小睡一下再說")
	else
		w:SetState(AfternoonState:new())
		w:WriteProgram()
	end
end

AfternoonState = State:new()

function AfternoonState:WriteProgram(w)
	if w.hour < 17 and w.hour >= 14 then
		print("下午寫代碼, 精神充足")
	else
		w:SetState(EveningState:new())
		w:WriteProgram()
	end
end

EveningState = State:new()

function EveningState:WriteProgram(w)
	if w.hour < 20 and w.hour >=17 then
		print("傍晚寫代碼,有點累,但還是繼續")
	else
		w:SetState(NightState:new())
		w:WriteProgram()
	end
end

NightState = State:new()

function NightState:WriteProgram(w)
	if w.hour < 22 and w.hour >= 20 then
		print("晚上寫代碼,苦逼啊")
	else
		w:SetState(MidnightState:new())
		w:WriteProgram()
	end
end

MidnightState = State:new()

function MidnightState:WriteProgram(w)
	if w.hour < 9 or w.hour >= 22 then
		print("深夜寫代碼,尼瑪,先睡醒了再說")
	else
		w:SetState(MorningState:new())
		w:WriteProgram()
	end
end

w = Work:new(nil,MorningState:new())
w:SetTime(21)
w:WriteProgram()

w:SetTime(18)
w:WriteProgram()

w:SetTime(10)
w:WriteProgram()

w:SetTime(13)
w:WriteProgram()

w:SetTime(15)
w:WriteProgram()

w:SetTime(23)
w:WriteProgram()

 

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved