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

狀態模式

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

在這裡插入圖片描述

優點

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

缺點

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

應用場景

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

代碼示例

在這裡插入圖片描述

這是一個狀態圖,具有 “有 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)

總結

本篇文章就到這裡瞭,希望能夠給你帶來幫助,也希望您能夠多多關註WalkonNet的更多內容!   

推薦閱讀: