状态模式通过接口与结构体实现订单状态流转,待支付、已支付、已发货、已完成状态分别封装行为,上下文代理操作至具体状态,实现解耦与可扩展。

状态模式是一种行为设计模式,适用于对象的行为依赖于其状态,并且在运行时根据状态改变行为的场景。在Go语言中,通过接口和结构体组合可以简洁地实现状态机。下面是一个基于Golang的状态模式示例,模拟一个订单的生命周期管理。
假设一个订单有以下几种状态:
每个状态下允许的操作不同,比如只有“待支付”状态才能执行“支付”,只有“已支付”才能“发货”等。
首先定义一个状态接口,所有具体状态需实现该接口的方法:
立即学习“go语言免费学习笔记(深入)”;
type OrderState interface {
Pay(order *OrderContext)
Ship(order *OrderContext)
Complete(order *OrderContext)
}
然后定义订单上下文,用于持有当前状态并代理操作到具体状态:
type OrderContext struct {
State OrderState
}
func (o *OrderContext) Pay() {
o.State.Pay(o)
}
func (o *OrderContext) Ship() {
o.State.Ship(o)
}
func (o *OrderContext) Complete() {
o.State.Complete(o)
}
每个状态实现对应的行为逻辑。例如,“待支付”状态:
type PendingState struct{}
func (s *PendingState) Pay(order *OrderContext) {
fmt.Println("订单已支付")
order.State = &PaidState{}
}
func (s *PendingState) Ship(order *OrderContext) {
fmt.Println("无法发货:订单尚未支付")
}
func (s *PendingState) Complete(order *OrderContext) {
fmt.Println("无法完成:订单尚未发货")
}
“已支付”状态:
type PaidState struct{}
func (s *PaidState) Pay(order *OrderContext) {
fmt.Println("订单已支付,无需重复支付")
}
func (s *PaidState) Ship(order *OrderContext) {
fmt.Println("订单已发货")
order.State = &ShippedState{}
}
func (s *PaidState) Complete(order *OrderContext) {
fmt.Println("无法完成:尚未发货")
}
“已发货”状态:
type ShippedState struct{}
func (s *ShippedState) Pay(order *OrderContext) {
fmt.Println("无法支付:订单已发货")
}
func (s *ShippedState) Ship(order *OrderContext) {
fmt.Println("无法重复发货")
}
func (s *ShippedState) Complete(order *OrderContext) {
fmt.Println("订单已完成")
order.State = &CompletedState{}
}
“已完成”状态:
type CompletedState struct{}
func (s *CompletedState) Pay(order *OrderContext) {
fmt.Println("订单已完成,无法再次支付")
}
func (s *CompletedState) Ship(order *OrderContext) {
fmt.Println("订单已完成,无法再次发货")
}
func (s *CompletedState) Complete(order *OrderContext) {
fmt.Println("订单已完成,无需重复操作")
}
初始化订单为“待支付”状态,并逐步执行操作:
func main() {
order := &OrderContext{
State: &PendingState{},
}
order.Pay() // 输出:订单已支付
order.Ship() // 输出:订单已发货
order.Complete()// 输出:订单已完成
order.Pay() // 输出:订单已完成,无法再次支付
}
输出结果:
订单已支付 订单已发货 订单已完成 订单已完成,无法再次支付
状态之间的转换由具体状态内部控制,上下文无需关心细节,符合开闭原则,新增状态也只需添加新结构体实现接口即可。
基本上就这些。这种设计让状态流转清晰,逻辑解耦,适合复杂状态流程的管理。不复杂但容易忽略的是状态切换时的边界校验和异常路径处理,实际项目中建议结合事件日志或状态迁移表增强可靠性。
以上就是Golang状态模式状态机设计与实现示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号