设计模式-状态模式-state-python

来源:互联网 发布:2017全国省市区数据库 编辑:程序博客网 时间:2024/06/09 18:17

def

当一个对象内在状态改变时允许其改变行为, 这个对象看起来像改变了其类。

usage

● 结构清晰
避免了过多的switch…case或者if…else语句的使用, 避免了程序的复杂性,提高系统的维护性。
● 遵循设计原则
很好地体现了开闭原则和单一职责原则, 每个状态都是一个子类, 你要增加状态就要增加子类, 你要修改状态, 你只修改一个子类就可以了。
● 封装性非常好
这也是状态模式的基本要求, 状态变换放置到类的内部来实现, 外部的调用不用知道类内部如何实现状态和行为的变换。

code

class State(object):    """Base state. This is to share functionality"""    def scan(self):        """Scan the dial to the next station"""        self.pos += 1        if self.pos == len(self.stations):            self.pos = 0        print(u"Scanning... Station is %s %s" %              (self.stations[self.pos], self.name))class AmState(State):    def __init__(self, radio):        self.radio = radio        self.stations = ["1250", "1380", "1510"]        self.pos = 0        self.name = "AM"    def toggle_amfm(self):        print(u"Switching to FM")        self.radio.state = self.radio.fmstateclass FmState(State):    def __init__(self, radio):        self.radio = radio        self.stations = ["81.3", "89.1", "103.9"]        self.pos = 0        self.name = "FM"    def toggle_amfm(self):        print(u"Switching to AM")        self.radio.state = self.radio.amstateclass Radio(object):    """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.amstate = AmState(self)        self.fmstate = FmState(self)        self.state = self.amstate    def toggle_amfm(self):        self.state.toggle_amfm()    def scan(self):        self.state.scan()# Test our radio outif __name__ == '__main__':    radio = Radio()    actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2    actions *= 2    for action in actions:        action()### OUTPUT #### Scanning... Station is 1380 AM# Scanning... Station is 1510 AM# Switching to FM# Scanning... Station is 89.1 FM# Scanning... Station is 103.9 FM# Scanning... Station is 81.3 FM# Scanning... Station is 89.1 FM# Switching to AM# Scanning... Station is 1250 AM# Scanning... Station is 1380 AM