狀態模式能夠看作是在運行時改變對象行爲的一種方式。狀態模式容許對象在其內部狀態變化時改變其行爲,此時感受就像對象自己已經改變了同樣。編碼
參與者:spa
優勢:code
缺點:對象
簡單示例:blog
""" 以電飯煲爲例,它有三種狀態或者說三種功能:煮飯、煮湯、煮粥 指定好電飯煲的狀態後,它就開始以對應模式進行工做 """ from abc import ABCMeta, abstractmethod class CookState(metaclass=ABCMeta): """State接口:定義狀態對象共有的接口,即須要煮什麼""" @abstractmethod def cook(self): pass class CookRice(CookState): """ConcreteSate對象:煮飯""" def cook(self): print('Cooking rice...') class CookSoup(CookState): """ConcreteSate對象:煮湯""" def cook(self): print('Cooking soup...') class CookPorridge(CookState): """ConcreteSate對象:煮粥""" def cook(self): print('Cooking porridge...') class Cooker: """Context對象:電飯煲,根據自身狀態決定煮什麼""" def __init__(self): # 定義自己具備的幾種狀態,或者電飯煲的幾種功能 self.states = [CookRice(), CookSoup(), CookPorridge()] self.state_index = 0 def switch_state(self): """切換電飯煲的狀態""" if self.state_index == (len(self.states) - 1): self.state_index = 0 else: self.state_index += 1 def start_cook(self): """開始工做""" self.states[self.state_index].cook() if __name__ == '__main__': cooker = Cooker() cooker.start_cook() cooker.switch_state() cooker.start_cook()