一、简介
状态模式一般用来实现状态机,而状态机常用在游戏、工作流引擎等系统开发中。不过,状态机的实现方式有多种,除了状态模式,比较常用的还有分支逻辑法和查表法。该模式允许对象内部状态改变使改变它的行为。
二、适用场景
- 行为随状态而改变
- 条件、分支语句的替代者
三、UML类图
四、案例
交通信号灯的红黄绿三色的变化。
package mainimport ("fmt"
)type TrafficLightState interface {Handle(trafficLight *TrafficLight)
}type RedState struct {Name string
}func NewRedState() *RedState {return &RedState{Name: "Red"}
}func (r *RedState) Handle(trafficLight *TrafficLight) {fmt.Println("Red light: Stopped")trafficLight.SetState(NewGreenState())
}type YellowState struct {Name string
}func NewYellowState() *YellowState {return &YellowState{Name: "Yellow"}
}func (y *YellowState) Handle(trafficLight *TrafficLight) {fmt.Println("Yellow light: Be prepared to stop")trafficLight.SetState(NewRedState())
}type GreenState struct {Name string
}func NewGreenState() *GreenState {return &GreenState{Name: "Green"}
}func (g *GreenState) Handle(trafficLight *TrafficLight) {fmt.Println("Green light: Go")trafficLight.SetState(NewYellowState())
}type TrafficLight struct {State TrafficLightState
}func NewTrafficLight() *TrafficLight {return &TrafficLight{State: NewRedState()}
}func (t *TrafficLight) SetState(state TrafficLightState) {t.State = state
}func (t *TrafficLight) Change() {t.State.Handle(t)
}func main() {trafficLight := NewTrafficLight()for i := 0; i < 10; i++ {trafficLight.Change()}
}