首頁 > 軟體

Python設計模式中的狀態模式你瞭解嗎

2022-02-15 13:02:33

狀態模式

狀態模式,當物件的內部狀態發生了改變的時候,允許物件執行不同的流程。

優點

  • 封裝了狀態轉換規則。
  • 列舉了可能的狀態,在列舉狀態之前需要確定狀態的種類。
  • 將所有與某個狀態有關的行為放到一個類中,並且可以方便地增加新的狀態,只需要改變物件狀態即可改變物件的行為。
  • 允許狀態轉換邏輯與狀態物件合成一體,而不是某一個巨大的條件語句塊。
  • 可以讓多個環境物件共用一個狀態物件,從而減少系統中物件的個數。

缺點

  • 狀態模式的使用必然會增加系統類和物件的個數。
  • 狀態模式的結構與實現都較為複雜,如果使用不當將導致程式結構和程式碼的混亂。
  • 狀態模式對 “開閉原則” 並不太好,對於可以切換狀態的狀態模式,增加新的狀態類需要修改那些負責狀態轉換的原始碼,否則無法切換到新增狀態,而且修改某個狀態類的行為也需修改對應類的原始碼。

應用場景

  • 行為隨狀態改變而改變的場景。
  • 條件、分支語句的代替者。

程式碼範例

這是一個狀態圖,具有 “有 25 分錢”、“沒有 25 分錢”、“售出糖果”、“糖果售罄” 這 4 個狀態。同時也對應 4 個動作:“投入 25 分錢”,“退回 25 分錢”,“轉動曲柄” 和 “發放糖果”。

class State:
    # 定義state基礎類別
    def insert_quarter(self):
        pass
    def eject_quarter(self):
        pass
    def turn_crank(self):
        pass
    def dispense(self):
        pass

class SoldOutState(State):
    # 繼承State 類
    def __init__(self, gumball_machine):
        self.gumball_machine = gumball_machine
    def __str__(self):
        return "sold_out"
    def insert_quarter(self):
        print("You can't insert a quarter, the machine is sold out")
    def eject_quarter(self):
        print("You can't eject, you haven't inserted a quarter yet")
    def turn_crank(self):
        print("You turned, but ther are no gumballs")
    def dispense(self):
        print("No gumball dispensed")

class SoldState(State):
    # 繼承State 類
    def __init__(self, gumball_machine):
        self.gumball_machine = gumball_machine
    def __str__(self):
        return "sold"
    def insert_quarter(self):
        print("Please wait, we're already giving you a gumball")
    def eject_quarter(self):
        print("Sorry, you already turned the crank")
    def turn_crank(self):
        print("Turning twice doesn't get you another gumball")
    def dispense(self):
        self.gumball_machine.release_ball()
        if gumball_machine.count > 0:
            self.gumball_machine.state = self.gumball_machine.no_quarter_state
        else:
            print("Oops, out of gumballs!")
            self.gumball_machine.state = self.gumball_machine.soldout_state

class NoQuarterState(State):
    # 繼承State 類
    def __init__(self, gumball_machine):
        self.gumball_machine = gumball_machine
    def __str__(self):
        return "no_quarter"
    def insert_quarter(self):
        # 投幣 並且改變狀態
        print("You inserted a quarter")
        self.gumball_machine.state = self.gumball_machine.has_quarter_state
    def eject_quarter(self):
        print("You haven't insert a quarter")
    def turn_crank(self):
        print("You turned, but there's no quarter")
    def dispense(self):
        print("You need to pay first")

class HasQuarterState(State):
    # 繼承State 類
    def __init__(self, gumball_machine):
        self.gumball_machine = gumball_machine
    def __str__(self):
        return "has_quarter"
    def insert_quarter(self):
        print("You can't insert another quarter")
    def eject_quarter(self):
        print("Quarter returned")
        self.gumball_machine.state = self.gumball_machine.no_quarter_state
    def turn_crank(self):
        print("You turned...")
        self.gumball_machine.state = self.gumball_machine.sold_state
    def dispense(self):
        print("No gumball dispensed")

class GumballMachine:
    def __init__(self, count=0):
        self.count = count
        # 找出所有狀態,並建立範例變數來持有當前狀態,然後定義狀態的值
        self.soldout_state = SoldOutState(self)
        self.no_quarter_state = NoQuarterState(self)
        self.has_quarter_state = HasQuarterState(self)
        self.sold_state = SoldState(self)
        if count > 0:
            self.state = self.no_quarter_state
        else:
            self.state = self.soldout_state
    def __str__(self):
        return ">>> Gumball machine current state: %s" % self.state
    def insert_quarter(self):
        # 投入25分錢
        self.state.insert_quarter()
    def eject_quarter(self):
        # 退回25分
        self.state.eject_quarter()
        # print("state", self.state, type(self.state))
    def turn_crank(self):
        # 轉動曲柄
        # print("state", self.state, type(self.state))
        self.state.turn_crank()
    def release_ball(self):
        # 發放糖果
        print("A gumball comes rolling out the slot...")
        if self.count > 0:
            self.count -= 1
        
if __name__ == "__main__":
    # 以下是程式碼測試
    gumball_machine = GumballMachine(5) # 裝入5 個糖果
    print(gumball_machine)
    gumball_machine.insert_quarter() # 投入25分錢
    gumball_machine.turn_crank() # 轉動曲柄
    print(gumball_machine)
    gumball_machine.insert_quarter() #投入25分錢
    gumball_machine.eject_quarter()  # 退錢
    gumball_machine.turn_crank()     # 轉動曲柄
    print(gumball_machine)
    gumball_machine.insert_quarter() # 投入25分錢
    gumball_machine.turn_crank() # 轉動曲柄 
    gumball_machine.insert_quarter() # 投入25分錢 
    gumball_machine.turn_crank()  # 轉動曲柄
    gumball_machine.eject_quarter() # 退錢
    print(gumball_machine)

總結

本篇文章就到這裡了,希望能夠給你帶來幫助,也希望您能夠多多關注it145.com的更多內容!   


IT145.com E-mail:sddin#qq.com