設計模式go語言實現----狀態模式State
阿新 • • 發佈:2018-12-19
1 定義
狀態模式(State): 當一個物件的內在狀態改變時允許改變其行為,這個物件看起來像是改變了其類
模式動機: 當控制一個物件狀態轉換的條件表示式過於複雜時,將狀態的判斷邏輯轉移道表示不同狀態的一系列類當中,可以把複雜的判斷邏輯簡化。
UML類圖: 狀態模式包含如下幾個角色:
- Context(環境類):維護一個ConcreteState子類的例項,這個例項定義當前的狀態
- State(抽象狀態類):定義一個介面以封裝與Context的一個特定狀態相關的行為
- ConcreteState(具體狀態類):每一個子類實現一個與Context的一個狀態相關的行為
下面以我們工作的狀態(隨著時間的變化,我們的工裝狀態是會不斷變化的)為例,其UML類圖如下:
2 go語言實現
2.1 實現Current
type Work struct { hour int current State finish bool } func (w *Work) SetState(s State) { w.current = s } func (w *Work) SetHour(hour int) { w.hour = hour } func (w *Work) SetFinishState(finish bool) { w.finish = finish } func (w Work) WriteProgram() { w.current.WriteProgram(w) }
2.2 實現State與ConcreteState
type State interface { WriteProgram(work Work) } type ForenoonState struct{} func (fs ForenoonState) WriteProgram(work Work) { if work.hour < 12 { fmt.Println("上午") } else { work.SetState(NoonState{}) work.WriteProgram() } } type NoonState struct{} func (ns NoonState) WriteProgram(work Work) { if work.hour < 13 { fmt.Println("中午") } else { work.SetState(AfternoonState{}) work.WriteProgram() } } type AfternoonState struct{} func (as AfternoonState) WriteProgram(work Work) { if work.hour < 17 { fmt.Println("下午") } else { work.SetState(EveningState{}) work.WriteProgram() } } type EveningState struct{} func (es EveningState) WriteProgram(work Work) { if work.finish { work.SetState(RestState{}) work.WriteProgram() } else { if work.hour < 21 { fmt.Println("晚間") } else { work.SetState(SleepingState{}) work.WriteProgram() } } } type SleepingState struct{} func (ss SleepingState) WriteProgram(work Work) { fmt.Println("睡著了") } type RestState struct{} func (rs RestState) WriteProgram(work Work) { fmt.Println("下班回家") }
2.3 客戶端呼叫
func main() {
tWork := state.Work{}
tState := state.ForenoonState{}
tWork.SetState(tState)
tWork.SetFinishState(true)
tWork.SetHour(22)
tWork.WriteProgram()
}