[go] 状态模式

简介: [go] 状态模式

状态模式


允许对象在内部状态改变时改变它的行为,对象看起来好像修改了它的类。


模型说明


https://pic4.58cdn.com.cn/nowater/webim/big/n_v2a8bbd22e4b0a43aabfc7ab4e94293461.png


  • 上下文 (Context) 保存了对于一个具体状态对象的引用, 并会将所有与该状态相关的工作委派给它。 上下文通过状态接口与状态对象交互, 且会提供一个设置器用于传递新的状态对象。
  • 状态 (State) 接口会声明特定于状态的方法。 这些方法应能被其他所有具体状态所理解, 因为你不希望某些状态所拥有的方法永远不会被调用。
  • 具体状态 (Concrete States) 会自行实现特定于状态的方法。 为了避免多个状态中包含相似代码, 你可以提供一个封装有部分通用行为的中间抽象类。
  • 状态对象可存储对于上下文对象的反向引用。 状态可以通过该引用从上下文处获取所需信息, 并且能触发状态转移。
  • 上下文和具体状态都可以设置上下文的下个状态, 并可通过替换连接到上下文的状态对象来完成实际的状态转换。


优缺点


1.优点


  • 单一职责原则: 将与特定状态相关的代码放在单独的类中。
  • 开闭原则: 无需修改已有状态类和上下文就能引入新状态。
  • 通过消除臃肿的状态机条件语句简化上下文代码。


2.缺点


  • 如果状态机只有很少的几个状态,或者很少发生改变,那么应用该模式可能会显得小题大作。


使用场景

  • 如果对象需要根据自身当前状态进行不同行为,同时状态的数量非常多且与状态相关的代码会频繁变更的话,可使用状态模式。
  • 如果某个类需要根据成员变量的当前值改变自身行为,从而需要使用大量的条件语句时,可使用该模式。
  • 当相似状态和基于条件的状态机转换中存在许多重复代码时,可使用状态模式。


参考代码


一台自动售货机上使用状态设计模式:

  • 有商品 (has­Item)
  • 无商品 (no­Item)
  • 商品已请求 (item­Requested)
  • 收到纸币 (has­Money)


同时, 自动售货机也会有不同的操作。 再一次的, 为了简单起见, 我们假设其只会执行 4 种操作:


  • 选择商品
  • 添加商品
  • 插入纸币
  • 提供商品


// vendingMachine.go 自动售货机
package main
import "fmt"
type VendingMachine struct {
 hasItem       State
 itemRequested State
 hasMoney      State
 noItem        State
 currentState State
 itemCount int
 itemPrice int
}
func newVendingMachine(itemCount, itemPrice int) *VendingMachine {
 v := &VendingMachine{
  itemCount: itemCount,
  itemPrice: itemPrice,
 }
 hasItemState := &HasItemState{
  vendingMachine: v,
 }
 itemRequestedState := &ItemRequestedState{
  vendingMachine: v,
 }
 hasMoneyState := &HasMoneyState{
  vendingMachine: v,
 }
 noItemState := &NoItemState{
  vendingMachine: v,
 }
 v.setState(hasItemState)
 v.hasItem = hasItemState
 v.itemRequested = itemRequestedState
 v.hasMoney = hasMoneyState
 v.noItem = noItemState
 return v
}
func (v *VendingMachine) requestItem() error {
 return v.currentState.requestItem()
}
func (v *VendingMachine) addItem(count int) error {
 return v.currentState.addItem(count)
}
func (v *VendingMachine) insertMoney(money int) error {
 return v.currentState.insertMoney(money)
}
func (v *VendingMachine) dispenseItem() error {
 return v.currentState.dispenseItem()
}
func (v *VendingMachine) setState(s State) {
 v.currentState = s
}
func (v *VendingMachine) incrementItemCount(count int) {
 fmt.Printf("Adding %d items\n", count)
 v.itemCount = v.itemCount + count
}
// state.go 状态接口
package main
type State interface {
 addItem(int) error
 requestItem() error
 insertMoney(money int) error
 dispenseItem() error
}
// noItemState.go 无商品状态
package main
import "fmt"
type NoItemState struct {
    vendingMachine *VendingMachine
}
func (i *NoItemState) requestItem() error {
    return fmt.Errorf("Item out of stock")
}
func (i *NoItemState) addItem(count int) error {
    i.vendingMachine.incrementItemCount(count)
    i.vendingMachine.setState(i.vendingMachine.hasItem)
    return nil
}
func (i *NoItemState) insertMoney(money int) error {
    return fmt.Errorf("Item out of stock")
}
func (i *NoItemState) dispenseItem() error {
    return fmt.Errorf("Item out of stock")
}
// hasItemState.go 有商品状态
package main
import "fmt"
type HasItemState struct {
 vendingMachine *VendingMachine
}
func (i *HasItemState) requestItem() error {
 if i.vendingMachine.itemCount == 0 {
  i.vendingMachine.setState(i.vendingMachine.noItem)
  return fmt.Errorf("No item present")
 }
 fmt.Printf("Item requestd\n")
 i.vendingMachine.setState(i.vendingMachine.itemRequested)
 return nil
}
func (i *HasItemState) addItem(count int) error {
 fmt.Printf("%d items added\n", count)
 i.vendingMachine.incrementItemCount(count)
 return nil
}
func (i *HasItemState) insertMoney(money int) error {
 return fmt.Errorf("Please select item first")
}
func (i *HasItemState) dispenseItem() error {
 return fmt.Errorf("Please select item first")
}
// itemRequestedState.go 请求商品
package main
import "fmt"
type ItemRequestedState struct {
 vendingMachine *VendingMachine
}
func (i *ItemRequestedState) requestItem() error {
 return fmt.Errorf("Item already requested")
}
func (i *ItemRequestedState) addItem(count int) error {
 return fmt.Errorf("Item Dispense in progress")
}
func (i *ItemRequestedState) insertMoney(money int) error {
 if money < i.vendingMachine.itemPrice {
  return fmt.Errorf("Inserted money is less. Please insert %d", i.vendingMachine.itemPrice)
 }
 fmt.Println("Money entered is ok")
 i.vendingMachine.setState(i.vendingMachine.hasMoney)
 return nil
}
func (i *ItemRequestedState) dispenseItem() error {
 return fmt.Errorf("Please insert money first")
}
// hasMoneyState.go 收到钱
package main
import "fmt"
type HasMoneyState struct {
 vendingMachine *VendingMachine
}
func (i *HasMoneyState) requestItem() error {
 return fmt.Errorf("Item dispense in progress")
}
func (i *HasMoneyState) addItem(count int) error {
 return fmt.Errorf("Item dispense in progress")
}
func (i *HasMoneyState) insertMoney(money int) error {
 return fmt.Errorf("Item out of stock")
}
func (i *HasMoneyState) dispenseItem() error {
 fmt.Println("Dispensing Item")
 i.vendingMachine.itemCount = i.vendingMachine.itemCount - 1
 if i.vendingMachine.itemCount == 0 {
  i.vendingMachine.setState(i.vendingMachine.noItem)
 } else {
  i.vendingMachine.setState(i.vendingMachine.hasItem)
 }
 return nil
}
// main.go 客户端
package main
import (
 "fmt"
 "log"
)
func main() {
 vendingMachine := newVendingMachine(1, 10)
 err := vendingMachine.requestItem()
 if err != nil {
  log.Fatalf(err.Error())
 }
 err = vendingMachine.insertMoney(10)
 if err != nil {
  log.Fatalf(err.Error())
 }
 err = vendingMachine.dispenseItem()
 if err != nil {
  log.Fatalf(err.Error())
 }
 fmt.Println()
 err = vendingMachine.addItem(2)
 if err != nil {
  log.Fatalf(err.Error())
 }
 fmt.Println()
 err = vendingMachine.requestItem()
 if err != nil {
  log.Fatalf(err.Error())
 }
 err = vendingMachine.insertMoney(10)
 if err != nil {
  log.Fatalf(err.Error())
 }
 err = vendingMachine.dispenseItem()
 if err != nil {
  log.Fatalf(err.Error())
 }
}


output:


Item requestd
Money entered is ok
Dispensing Item
Adding 2 items
Item requestd
Money entered is ok
Dispensing Item
相关文章
|
4月前
|
SQL Java 数据库连接
【ORM 框架】MyBatis-Plus 核心特性、条件构造器、分页插件、乐观锁插件(附《思维导图》、《问题排查与实践清单》和《面试高频考点汇总》)
MyBatis-Plus 是一款遵循“只增强、不改变”原则的 MyBatis 增强工具,提供无侵入、低损耗的通用 CRUD、Lambda 条件构造、分页、逻辑删除、乐观锁、自动填充及代码生成等能力,大幅提升单表开发效率,是国内主流 Java ORM 增强框架。
|
4月前
|
传感器 人工智能 算法
GEO优化:如何提升内容在AI答案中的权重排名
本文详解GEO(生成式引擎优化)核心:提升内容在AI答案中的“被引用权重”。不求排名靠前,而求成为答案支柱——被提及、被多提、被当结论依据。聚焦五大关键:可核实证据、可信身份、易抽取结构、意图精准匹配、内容新鲜准确。附实操八步与避坑指南,助你让AI“非选你不可”。
362 1
|
5月前
|
人工智能 运维 安全
2026年OpenClaw(小龙虾)推荐:主流产品对比与选型指南
2026年爆火的“小龙虾”(OpenClaw)是开源AI智能体框架,让大模型从对话工具升级为能操作电脑、跨软件办公的数字员工。本文横向评测国内外11款主流产品——AionClaw(全能本地版)、ShellMate(终端轻量)、FlowMind(可视化工作流)等,覆盖开发者、运营、个人及企业场景,助你选对AI智能体。
|
6月前
|
人工智能 供应链 监控
1688 运营学习指南,一站式成长平台 1688 运营研究社深度解析
1688运营研究社是专注B2B电商的垂直赋能平台,为源头工厂与中小企业提供系统化课程、45个实战社群陪跑、免费数据工具及生态资源对接;同步助力代运营、供应链等服务商精准获客、高效合作。已服务超10万商家、百家服务商,真正打通“学习—实操—资源—增长”闭环。
647 3
|
5月前
|
自然语言处理 API Android开发
别再幻想"App一键上架"了——为什么应用发布做不到全自动
应用商店“一键上架”为何难实现?根本原因在于各大平台API不支持全流程自动化:首次上架需手动创建应用、填写备案/资质/分级等合规信息,且人工审核不可绕过。9大主流渠道中8个强制人工介入,自动化仅限于传包、状态同步等有限环节。
475 0
|
5月前
|
弹性计算 监控 Kubernetes
阿里云SAE应用引擎弹性扩缩容完全指南:从手动调优到智能自动化
本文全面解析阿里云Serverless应用引擎SAE的弹性扩缩容体系。从手动扩缩的应急操作入手,深入剖析定时弹性、监控指标弹性与混合弹性三大自动策略的配置方法与适用场景。详细解读弹性步长、稳定窗口、禁止缩容等高级参数的调优技巧,并揭示SAE弹性策略与Kubernetes HPA的映射关系。文章还涵盖基于Prometheus自定义指标的弹性扩展、通过Terraform和saectl工具实现基础设施即代码的自动化管理,以及弹性可观测性的最佳实践。结合电商大促、视频直播等真实场景,提供从基础配置到生产级优化的完整路径,帮助读者在保障应用稳定性的同时实现资源利用最大化与成本最优化。
|
6月前
|
存储 文字识别 BI
内网 RPA 私有化部署实战:数据不出域的完整落地方案
摘要: 本文从企业内网安全合规角度出发,梳理 RPA 内网私有化部署的核心诉求与选型要点,结合真实落地场景提供可复用的部署思路,帮助技术团队在不依赖外部云服务的前提下实现流程自动化。
546 0
|
7月前
|
存储 人工智能 编解码
意图共鸣科技《AI记忆链商业化白皮书2.0》深度:三元悖论,从订阅制到双轨制的范式转移
本文揭示AI订阅制的“三元悖论”:用户不敢深用、企业难盈利、数据难自主。根源在于固定收费与浮动算力成本的根本错配。借鉴电信模式,提出“双轨制”——月租保记忆(存储)、按Token付费(算力),实现公平、透明、可迁移、可持续的新范式。
649 6
|
6月前
|
JavaScript Windows
Node.js v0.12.2 安装教程(Windows x86版 node-v0.12.2-x86.msi 详细步骤)
本教程详解Node.js v0.12.2(32位)Windows安装全流程:含管理员运行、协议确认、路径设置、组件默认安装及cmd验证(node -v / npm -v),步骤清晰,零基础可操作。(238字)
|
存储 编解码 vr&ar
色彩空间与像素格式
颜色是不同波长的光对人眼刺激产生的色彩感觉。色彩空间(Color Space)是颜色的数学表示,根据不同的表示方法分为不同的色彩模型。最常用的色彩模型有三类:RGB(用于计算机图形学), YUV(用于视频系统), CMYK(用于彩色印刷)。后文对色彩空间与色彩模型的叫法不作区分。本文仅讨论视频图像处理领域常用的 RGB 色彩空间和 YUV 色彩空间。
3892 0
色彩空间与像素格式