设计模式-行为型模式,状态模式(14)
2018-03-08 13:37
489 查看
在状态模式(State Pattern)中,类的行为是基于它的状态改变的。这种类型的设计模式属于行为型模式。
在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
在状态模式中,我们创建表示各种状态的对象和一个行为随着状态对象改变而改变的 context 对象。
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("Scanning... Station is", 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("Switching to FM") self.radio.state = self.radio.fmstate class 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("Switching to AM") self.radio.state = self.radio.amstate class 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 out if __name__ == '__main__': radio = Radio() actions = [radio.scan] * 2 + [radio.toggle_amfm] + [radio.scan] * 2 actions = actions * 2 for action in actions: action()
相关文章推荐
- 设计模式笔记(14)---模板方法模式(行为型)
- 设计模式(20)-行为型-状态模式(State)
- 行为型:设计模式之状态模式(十八)
- 23种设计模式4--行为型模式(策略模式、模板方法模式、观察者模式、迭代子模式、责任链模式、命令模式、备忘录模式、状态模式、访问者模式、中介者模式、解释器模式)
- 【设计模式】学习笔记14:状态模式(State)
- java设计模式--行为型模式--状态模式
- 【设计模式】—-(20)状态模式(行为型)
- 设计模式 之 STATE(状态)实例 —对象行为型模式
- 设计模式(14) - State状态模式
- 设计模式-行为型模式-状态模式
- 设计模式 ( 十八 ):State状态模式 -- 行为型
- GoF23种设计模式之行为型模式之状态模式
- 设计模式 ( 十七) 状态模式State(对象行为型)
- Java设计模式之行为型模式(状态模式)
- JAVA设计模式(18):行为型-状态模式(State)
- GoF23种设计模式之行为型模式之状态模式
- 23种设计模式(14)_行为型_命令模式(Command Pattern)
- 二十三种设计模式之行为型模式之状态模式
- 设计模式--状态模式State(行为型)
- GoF23种设计模式之行为型模式之状态模式