Python 设计模式 - 状态模式(State Pattern)
状态模式(State Pattern)是当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类。
状态模式主要解决的是当控制一个对象状态的条件表达式过于复杂时的情况。把状态的判断逻辑转移到表示不同状态的一系列类中,可以把复杂的判断逻辑简化。
Python 如何实现状态模式?
状态模式的基本实现如下所示 −
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)
输出
以上程序生成如下输出 −