Golang - Design Pattern #24: HSM(Hierarchical State Machine)

2023/09/02閱讀時間約 4 分鐘
raw-image


🌲 結構化狀態機 🌲



在物件導向的世界中,物件的行為會基於它的狀態而改變。當我們面臨更多的狀態和轉換時,狀態機就成為必要,而HSM(Hierarchical State Machine,層次狀態機)模式更是一個進一步的解決方案,它以層次化的方式組織狀態。


HSM 🌲

HSM 在傳統的狀態機上加上層次結構。這種層次結構的好處是可以共享行為,並允許子狀態繼承或覆蓋父狀態的行為。

特點:

  1. 行為繼承:子狀態可以繼承父狀態的行為。
  2. 狀態共享:多個子狀態可以共享相同的行為。
  3. 本地處理:事件可以在當前狀態、父狀態或更高的層次上進行處理。


Going

🚦 紅綠燈

想像一個城市交通燈系統。燈有三種主要狀態:紅燈、黃燈和綠燈。但在每個主要狀態下,都有子狀態,例如:綠燈下有“直行”和“左轉”。
type State interface {
Handle(context *TrafficLightContext)
}

type RedLightState struct{}
func (r *RedLightState) Handle(context *TrafficLightContext) {
// handle red light logic
}

type GreenLightState struct{}
func (g *GreenLightState) Handle(context *TrafficLightContext) {
// handle green light logic
}

type TrafficLightContext struct {
state State
}
func (c *TrafficLightContext) SetState(state State) {
c.state = state
}
func (c *TrafficLightContext) Request() {
c.state.Handle(c)
}

🎮 遊戲角色

在一款遊戲中,玩家角色可能會有多種狀態,例如“站立”、“跑動”、“跳躍”和“受傷”。但在“跑動”狀態中,可能還有子狀態,例如“快跑”和“慢跑”。


type State interface {
Handle(context *GameCharacterContext)
}

type StandingState struct{}
func (s *StandingState) Handle(context *GameCharacterContext) {
// handle standing logic
}

type RunningState struct{}
func (r *RunningState) Handle(context *GameCharacterContext) {
// handle general running logic
}

type SprintingState struct{}
func (s *SprintingState) Handle(context *GameCharacterContext) {
// handle sprinting logic under running
}

type JoggingState struct{}
func (j *JoggingState) Handle(context *GameCharacterContext) {
// handle jogging logic under running
}

type GameCharacterContext struct {
state State
}
func (c *GameCharacterContext) SetState(state State) {
c.state = state
}
func (c *GameCharacterContext) ExecuteAction() {
c.state.Handle(c)
}


結論 🌟

HSM 在處理複雜的狀態邏輯時提供了結構化和直觀的方式。層次狀態機的概念使得行為重用和狀態管理更加清晰。對於那些有許多相互依賴的狀態和轉換的系統,HSM 提供了一個有效的解決方案。



感謝

謝謝大家看完這篇,如果您喜歡我的文章,歡迎 小額贊助我 ^^

30會員
193內容數
歡迎來到【代碼的詩情】:探索程式語言之美 系列,這是一場優雅的程式之旅,透過詩歌的抒發,尋找不同程式語言的美感和精髓。 在這個系列中,我們將透過文字的韻律,深入探索多種程式語言的核心概念和語法,以及它們獨特的應用和技巧。每一篇詩歌都是一個故事,每一段代碼都是一句詩句,讓代碼的旋律和詩情在其中相互交織。
留言0
查看全部
發表第一個留言支持創作者!