设计模式-状态模式

设计模式-状态模式

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-nrZsJWTA-1660695785315)(https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ82R6fGn9BnYHKwf5IsnT6iXPWrfXdwW-4yg&usqp=CAU)]

参考


在状态模式中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的context对象。

使用场景

  • 行为随状态改变而改变的场景
  • 条件、分支语句的代替者

Demo分析

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-76JHpHzv-1660695785316)(C:\Users\86136\AppData\Roaming\Typora\typora-user-images\image-20220816164812719.png)]

分析:

我们将创建一个State接口和实现了State接口的实体状态类。Context是一个带有某个状态的类。

Go实现

package main

import "fmt"

/**
* 状态接口
 */
type State interface {
	doAction(c Context)
}

type StartState struct{}

func (s *StartState) doAction(c Context) {
	fmt.Println("StartState")
	c.setState(s)
}

type StopState struct{}

func (s *StopState) doAction(c Context) {
	fmt.Println("StopState")
	c.setState(s)
}

/**
 * Context类
 */
type Context struct {
	state State
}

func (c *Context) setState(state State) {
	c.state = state
}

func (c *Context) getState() *State {
	return &c.state
}

func statePatternDemo() {
	context := &Context{}
	startState := &StartState{}
	stopState := &StopState{}
	startState.doAction(*context)
	stopState.doAction(*context)
}

func main() {
	statePatternDemo()
}

输出

StartState
StopState

Python实现

class State(object):
  """
    ## 状态的抽象类
  """
  def adAction(self, action):
    pass

class Context(object):
  def __init__(self):
    self.state = None
  def setState(self, state):
    self.state = state
  def getState(self):
    return self.state

class StartState(State):
  def adAction(self, action):
    print("Start state")
    action.setState(self )

class StopState(State):
  def adAction(self, action):
    print("Stop state")
    action.setState(self)

def test():
  context = Context()
  startState = StartState()
  stopState = StopState()
  startState.adAction(context)
  stopState.adAction(context)

if __name__ == '__main__':
  test()

输出

Start state
Stop state

小结

通过状态模式,将状态对象独立于Contex对象方便了状体的管理。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值