鍍金池/ 教程/ Python/ 狀態(tài)設計模式
反模式
隊列
適配器設計模式
享元設計模式
Python設計模式
工廠模式
模板設計模式
構建器(Builder)設計模式
Python設計模式概要
命令設計模式
Python設計模式簡介
觀察者設計模式
代理設計模式
異常處理
責任鏈設計模式
字典實現(xiàn)
抽象工廠設計模式
Python并發(fā)(多線程)
策略設計模式
門面(Facade)設計模式
原型設計模式
迭代器設計模式
集合
單例模式
列表數(shù)據(jù)結構
狀態(tài)設計模式
模型視圖控制器(MVC)模式
裝飾器設計模式
面向?qū)ο蟾拍畹膶崿F(xiàn)
面向?qū)ο笤O計模式
字符串和序列化

狀態(tài)設計模式

它為狀態(tài)機提供了一個模塊,它使用從指定的狀態(tài)機類派生而來的子類來實現(xiàn)。 這些方法獨立于狀態(tài),并使用裝飾器聲明轉(zhuǎn)換。

如何實現(xiàn)狀態(tài)模式?

狀態(tài)模式的基本實現(xiàn),請參考如下代碼 -

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)

執(zhí)行上述程序生成以下輸出 -