400 8949 560

NEWS/新闻

分享你我感悟

您当前位置> 主页 > 新闻 > 技术开发

如何使用Golang实现状态模式行为管理_Golang状态模式对象切换示例

发表时间:2026-01-01 00:00:00

文章作者:P粉602998670

浏览次数:

状态模式在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 处理,形成清晰的责任链。

  • 避免直接 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 同时操作同一台 *VendingMachinesetState() 和状态方法调用之间存在竞态——比如 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),就要警惕——那可能已经不是状态,而是上下文数据了。

相关案例查看更多