Python 状态模式

它为状态机提供了一个模块,该模块使用从指定状态机类派生的子类实现。这些方法与状态无关,并导致使用装饰器声明转换。

如何实现状态模式?

状态模式的基本实现如下所示:

# Filename : example.py
# Date : 2020-08-22
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
class Off(ComputerState):
    name = "off"
    allowed = ['on']
class On(ComputerState):
    """ State of being powered on and working """
    name = "on"
    allowed = ['off','suspend','hibernate']
class Suspend(ComputerState):
    """ State of being in suspended mode after switched on """
    name = "suspend"
    allowed = ['on']
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)
if __name__ == "__main__":
    comp = Computer()
    comp.change(On)
    comp.change(Off)
    comp.change(On)
    comp.change(Suspend)
    comp.change(Hibernate)
    comp.change(On)
    comp.change(Off)

输出

上面的程序生成以下输出:

Current: off => switched to new state on
Current: on => switched to new state off
Current: off => switched to new state on
Current: on => switched to new state suspend
Current: suspend => switching to hibernate not possible.
Current: suspend => switched to new state on
Current: on => switched to new state off

下一章:Python 策略模式

策略模式是一种行为模式。策略模式的主要目标是使客户能够选择不同的算法或过程来完成指定的任务。可以针对上述任务交换不同的算法而不会带来任何复杂性。当访问外部资源时,此模式可用于提高灵活性。 如何实施策略模式? ...