状态模式
发布时间 : 2024-09-16 03:42
阅读 :
State Pattern 状态模式把对象每一个状态的行为封装在对象内部。避免大量状态逻辑杂糅。
实现 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 package stateimport "fmt" type State interface { NextState()State Update() } type GameStartState struct {} type GameRunState struct {} type GameEndState struct {} func (this *GameStartState) NextState()State{ fmt.Println("Start Next" ) return new (GameRunState) } func (this *GameStartState) Update(){ fmt.Println("Game Start" ) } func (this *GameRunState) NextState()State{ fmt.Println("Run Next" ) return new (GameEndState) } func (this *GameRunState) Update(){ fmt.Println("Run" ) } func (this *GameEndState) NextState()State{ return new (GameStartState) } func (this *GameEndState) Update(){ fmt.Println("End" ) }
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 package mainimport ( "projects/DesignPatternsByGo/behavioralPatterns/state" "time" ) func stateMechine (state state.State, ch chan int ) { for { select { case i := <-ch: if i == 1 { state = state.NextState() } else if i == 0 { return } default : state.Update() } } } func main () { st := new (state.GameStartState) ch := make (chan int ) go stateMechine(st, ch) time.Sleep(time.Second * 3 ) ch <- 1 time.Sleep(time.Second * 3 ) ch <- 1 time.Sleep(time.Second * 3 ) ch <- 0 time.Sleep(time.Second * 3 ) }
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以邮件