# -*- coding:UTF-8 -*- import abc class State(metaclass=abc.ABCMeta): @abc.abstractmethod def handle(self, context): pass class ConcreteStateA(State): def handle(self, context): context.state = ConcreteStateB() class ConcreteStateB(State): def handle(self, context): context.state = ConcreteStateA() class Context: def __init__(self, state): self.__state = state @property def state(self): return self.__state @state.setter def state(self, value): self.__state = value print("当前状态:%s" % self.__state.__class__.__name__) def request(self): self.__state.handle(self) if __name__ == "__main__": c = Context(ConcreteStateA()) c.request() c.request() c.request() c.request() c.request()