状态模式在Go中应基于组合而非继承,通过接口定义行为、结构体实现状态逻辑,并由上下文封装受控的状态切换,避免条件分支与并发竞态。

状态模式的核心不是继承而是组合
Go 没有传统面向对象的继承机制,强行模仿 State 抽象类 + 子类重写会写出反模式代码。正确做法是让上下文(如 *VendingMachine)持有一个 State 接口类型的字段,所有状态行为由独立结构体实现该接口,通过替换该字段完成“切换”。
关键点在于:状态变更必须由当前状态自己决定是否允许、以及切换成谁——不能由外部直接赋值新状态,否则会绕过状态转移规则。
定义 State 接口与具体状态结构体
接口方法应覆盖所有可能被触发的行为,比如投币、退币、选择商品、出货等;每个具体状态只实现它“合法响应”的方法,其余返回错误或静默忽略(取决于业务需求)。
-
IdleState允许InsertCoin(),但拒绝Dispense() -
HasCoinState允许SelectItem()和Refund(),但拒绝重复InsertCoin() - 所有状态都应持有对上下文的弱引用(如
*VendingMachine),用于调用setState()
type State interface {
InsertCoin(m *VendingMachine)
SelectItem(m *VendingMachine, item string)
Dispense(m *VendingMachine)
Refund(m *VendingMachine)
}
type IdleState struct{}
func (s *IdleState) InsertCoin(m *VendingMachine) {
m.setState(&HasCoinState{})
fmt.Println("✅ 已投币,进入待选商品状态")
}
func (s *IdleState) SelectItem(m *VendingMachine, item string) {
fmt.Println("❌ 请先投币")
}
func (s *IdleState) Dispense(m *VendingMachine) {
fmt.Println("❌ 无法出货:未投币且未选品")
}
func (s *IdleState) Refund(m *VendingMachine) {
fmt.Println("❌ 无法退币:当前无币")
}
上下文需封装状态切换逻辑
VendingMachine 不暴露 state 字段,只提供受控的 setState() 方法,并在其中做空值/非法状态校验。每次行为方法(如 InsertCoin())都委托给当前 state 处理,形成清晰的责任链。
立即学习“go语言免费学习笔记(深入)”;
- 避免直接
m.state = &NewState{},必须走setState() -
setState()内可加日志、审计或状态变更钩子(如通知观察者) - 初始化时必须设置初始状态,否则调用会 panic
type VendingMachine struct {
state State
}
func NewVendingMachine() *VendingMachine {
return &VendingMachine{
state: &IdleState{},
}
}
func (m *VendingMachine) setState(s State) {
if s == nil {
panic("state cannot be nil")
}
m.state = s
}
func (m *VendingMachine) InsertCoin() {
m.state.InsertCoin(m)
}
func (m *VendingMachine) SelectItem(item string) {
m.state.SelectItem(m, item)
}
func (m *VendingMachine) Dispense() {
m.state.Dispense(m)
}
func (m *VendingMachine) Refund() {
m.state.Refund(m)
}
容易踩的坑:共享状态与并发安全
如果多个 goroutine 同时操作同一台 *VendingMachine,setState() 和状态方法调用之间存在竞态——比如 A 刚判断完 state == &HasCoinState{},B 就把它切成了 &SoldOutState{},A 接着调用 Dispense() 就可能失败或逻辑错乱。
- 最简方案:用
sync.Mutex包裹所有公开方法(InsertCoin()等) - 更优方案:将状态变更建模为事件,用 channel + 单 goroutine 串行处理(类似 actor 模型)
- 切忌在状态方法内部启动 goroutine 并异步修改
m.state,这会让状态流不可预测
状态模式的价值不在“看起来像 UML 图”,而在把分散的 if state == X { ... } else if state == Y { ... } 条件分支,收束到一个个独立、可测试、可替换的结构体中。一旦开始往状态里塞字段(比如 coinCount int),就要警惕——那可能已经不是状态,而是上下文数据了。










