首页 > 编程语言 >Python: State Pattern

Python: State Pattern

时间:2022-10-26 23:56:35浏览次数:58  
标签:Python Pattern self state State context class def

GeovinDuState.py

#状态模式 State  Pattern
class ComputerState(object):
    name = "state"
    allowed = []

    def switch(self, state):
        """ Switch to new state """
        if state.name in self.allowed:
            print
            'Current:', self, ' => switched to new state', state.name
            self.__class__ = state
        else:
            print
            'Current:', self, ' => switching to', state.name, 'not possible.'

def __str__(self):
        return self.name

# ComputerState
class Off(ComputerState):

   name = "off"
   allowed = ['on']

# ComputerState
class On(ComputerState):
    """ State of being powered on and working """
    name = "on"
    allowed = ['off', 'suspend', 'hibernate']

# ComputerState
class Suspend(ComputerState):
    """ State of being in suspended mode after switched on """
    name = "suspend"
    allowed = ['on']

# ComputerState
class Hibernate(ComputerState):
    """ State of being in hibernation after powered on """
    name = "hibernate"
    allowed = ['on']


class Computer(object):
    """ A class representing a computer """

    def __init__(self, model='HP'):
        self.model = model
        # State of the computer - default is off.
        self.state = Off()

    def change(self, state):
        """ Change state """
        self.state.switch(state)


"""2 State class: Base State class"""


class DuState:
    """Base state. This is to share functionality"""

    def scan(self):
        """Scan the dial to the next station"""
        self.pos += 1

        """check for the last station"""
        if self.pos == len(self.stations):
            self.pos = 0
        print("Visiting... Station is {} {}".format(self.stations[self.pos], self.name))


"""Separate Class for AM state of the radio"""


class AmState(DuState):
    """constructor for AM state class"""

    def __init__(self, radio):
        self.radio = radio
        self.stations = ["1250", "1380", "1510"]
        self.pos = 0
        self.name = "AM"

    """method for toggling the state"""

    def toggle_amfm(self):
        print("Switching to FM")
        self.radio.state = self.radio.fmstate


"""Separate class for FM state"""


class FmState(DuState):
    """Constriuctor for FM state"""

    def __init__(self, radio):
        self.radio = radio
        self.stations = ["81.3", "89.1", "103.9"]
        self.pos = 0
        self.name = "FM"

    """method for toggling the state"""

    def toggle_amfm(self):
        print("Switching to AM")
        self.radio.state = self.radio.amstate


"""Dedicated class Radio"""


class Radio:
    """A radio. It has a scan button, and an AM / FM toggle switch."""

    def __init__(self):
        """We have an AM state and an FM state"""
        self.fmstate = FmState(self)
        self.amstate = AmState(self)
        self.state = self.fmstate

    """method to toggle the switch"""

    def toggle_amfm(self):
        self.state.toggle_amfm()

    """method to scan """

    def scan(self):
        self.state.scan()

# Geovin Du 3
class Context:
    _state = None
    """ A reference to the current state."""

    def __init__(self, state):
        self.transition_to(state)

    def transition_to(self, state):
        """Method to make transition"""

        print(f"Context: Transition to {type(state).__name__}")
        self._state = state
        self._state.context = self

    def request1(self):
        self._state.handle1()

    def request2(self):
        self._state.handle2()


class GeovinState:
    """An abstract class for Concrete sub-classes"""

    @property
    def context(self):
        return self._context

    @context.setter
    def context(self, context: Context):
        self._context = context

    # @abstractmethod
    def handle1(self):
        pass

    # @abstractmethod
    def handle2(self):
        pass

class State_A(GeovinState):
    def handle1(self):
        print("State_A handles request1.")
        print("State_A wants to change the state of the context.")
        self.context.transition_to(State_B())

    def handle2(self):
        print("State_A handles request2.")

class State_B(GeovinState):
    def handle1(self):
        print("State_B handles request1.")

    def handle2(self):
        print("State_B handles request2.")
        print("State_B wants to change the state of the context.")
        self.context.transition_to(State_A())

  

main.py 调用:

# 状态模式 State  Pattern
comp = GeovinDuState.Computer()
comp.change(GeovinDuState.On)
comp.change(GeovinDuState.Off)
comp.change(GeovinDuState.On)
comp.change(GeovinDuState.Suspend)
comp.change(GeovinDuState.Hibernate)
comp.change(GeovinDuState.On)
comp.change(GeovinDuState.Off)

radio = GeovinDuState.Radio()
actions = [radio.scan] * 3 + [radio.toggle_amfm] + [radio.scan] * 3
actions *= 2

for action in actions:
     action()

context = GeovinDuState.Context(GeovinDuState.State_A())
context.request1()
context.request2()

  

输出

Visiting... Station is 89.1 FM
Visiting... Station is 103.9 FM
Visiting... Station is 81.3 FM
Switching to AM
Visiting... Station is 1380 AM
Visiting... Station is 1510 AM
Visiting... Station is 1250 AM
Visiting... Station is 1380 AM
Visiting... Station is 1510 AM
Visiting... Station is 1250 AM
Switching to FM
Visiting... Station is 89.1 FM
Visiting... Station is 103.9 FM
Visiting... Station is 81.3 FM
Context: Transition to State_A
State_A handles request1.
State_A wants to change the state of the context.
Context: Transition to State_B
State_B handles request2.
State_B wants to change the state of the context.
Context: Transition to State_A

  

标签:Python,Pattern,self,state,State,context,class,def
From: https://www.cnblogs.com/geovindu/p/16830610.html

相关文章

  • Python系列(4)- 使用 MoviePy 编辑视频
    MoviePy是一个用于视频编辑的Python模块,可用于进行视频的基本操作(如剪切、连接、标题插入)、视频合成(也称非线性编辑)、视频处理或创建高级效果。MoviePy能处理的视频是......
  • JDBC 的API之 Connection 和 Statement
     Connection是建立连接的api他有两个功能: 一是:建立和数据库的连接:Connectionconn=DriverManager.getConnection(url,root,password); 二是:管理事务,就是在java......
  • spring升级后,useSuffixPatternMatch默认为false,导致test.do匹配不到test
    问题:spring升级后,发现useSuffixPatternMatch默认为false,导致test.do匹配不到test了原因:RequestMappingHandlerMapping.useSuffixPatternMatch(使用后缀模式匹配)在sp......
  • python爬虫获取tap帖子
    1.tap帖子数据获取代码中cookie为登陆后页面抓包的cookie,其中详情页需要3种拼接url,第一种是链接中含有topic,第二种中含有moment,第三种是视频,其中含有videoimportr......
  • Python: Template Method Pattern
    GeovinDuTemplate.py#模板方法模式TemplateMethodPatterndefget_text():return"text文件""""methodtogetthexmlversionoffile"""......
  • 我的爱情与Python不得不说的故事
    最近,沉迷于辩论比赛,有最近有场辩论赛因为一句话出圈了:为什么是坠入爱河而不是跳入爱河呢?因为爱本身是自由意志的沉沦。这让我想起来我当时坠入爱河的时候,作为人家印象里呆板......
  • 学习python-Day80
    今日学习内容一、表单控制二、购物车案例三、v-model进阶(了解)四、vue生命周期五、与后端交互ajaz六、计算属性七、侦听属性......
  • Python进阶篇04-面向对象编程
    面向对象编程面向对象编程和面向过程编程的区别:类和实例类:抽象的、用于创建实例的基础模板,类里面可以定义这个类所拥有的基础的属性。实例:根据类而创建的具体的对象,实......
  • python基础之模块
    第三方模块的下载与使用第三方模块:别人写的模块一般情况下功能特别强大想使用第三方模块必须先下载后面才可以反复使用方式1:命令行借助于pip工具pip......
  • OpenCV-Python learning-9.图像阈值处理
    你也可以​​iframe外链​​查看。本节内容包括:常用阈值方法自适应阈值Otsu(大津法)自适应阈值​​github地址​​......