亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Python 中的狀態模式

Python 中的狀態模式

慕無忌1623718 2021-09-11 16:04:45
我在用 Python 實現狀態設計模式時遇到了一些問題。我是 Python 的新手,并編寫了一些代碼來嘗試回答提出給我的這個問題:為一個簡單的 ATM 編寫代碼,允許用戶插入他們的卡、輸入他們的 PIN、請求現金和彈出卡。將以下對象模型用于顯示狀態模式使用的系統。您需要確定每個操作要更改為什么狀態。請參閱下面的 UML 圖以獲取更多信息:下面是我的嘗試...import reclass AtmState(object):    name = "ready"    allowed = []    def switch(self, state):        """ Switch to new state """        if state.name in self.allowed:#             print("Current {} => switched to new state {}.".format(self, state.name))            self.__class__=state# These print statements show how you switch between states.#         else:#             print("Current {} => switched to {} not possible.".format(self, state.name))    def getState(self):        print("The current state is {}".format(self.state))    def __str__(self):        return self.name    def __repr__(self):        return r"The ATM is in a {} state.".format(self.state)    def insertCard(self, card):        # Set messages for card format and inserted        wrong_format = "Please insert your card in the following format: XXXX-XXXX-XXXX-XXXX."        card_inserted = "Card Inserted: {}"        card_pattern='^([0-9]{4})(-?|\s)([0-9]{4})(-?|\s)([0-9]{4})(-?|\s)([0-9]{4})$'        pattern = re.compile(card_pattern)        if pattern.match(card) and str(self.state) in ["insert", "ready", "no card"]:            self.state.switch(HasCard)            print(card_inserted.format(card))            self.state.switch(HasPin)        elif pattern.match(card)==False and str(self.state) ["insert", "ready", "no card"]:            print(wrong_format)        elif str(self.state) in ["enter_pin", "withdraw"]:            print("Card already inserted")        elif str(self.state) in ["no card"]:            print("Error: No Card Inserted. Please insert card.")對我來說最大的困惑是如何使用類來實現它?我能夠獲得正確的邏輯,但我正在努力使用狀態設計模式進行實現。任何指導將不勝感激。
查看完整描述

2 回答

?
嚕嚕噠

TA貢獻1784條經驗 獲得超7個贊

這是您問題的簡化版本的python3中的快速而骯臟的實現。


State 是一個抽象類,使用(Mickeal 描述的 abc 包)充當接口(派生類必須實現抽象方法)。實際狀態接收請求并實現函數并執行狀態轉換這就是為什么我將 atm 對象作為參數方法傳遞


import abc

class State(object,metaclass = abc.ABCMeta):

    @abc.abstractmethod

    def eject(self, atm):

        raise NotImplementedError('')

    @abc.abstractmethod

    def insert(self, atm):

        raise NotImplementedError('')



class NoCard(State):

    def eject(self, atm):

        print('Error : no card')

    def insert(self, atm):

        print('ok')

        atm.state  = HasCard()


class HasCard(State):

    def eject(self, atm):

        print('ok')

        atm.state = NoCard()

    def insert(self, atm):

        print('Error : card already present')



class ATM:

    def __init__(self):

        self.state = NoCard()

    def insert(self):

        self.state.insert(self)

    def eject(self):

        self.state.eject(self)


if __name__ == "__main__":

    atm = ATM()

    atm.eject() # default state is no card error no card

    atm.insert() # ok state is has card

    atm.insert() # error  card already in

    atm.eject() # ok  state become no card

    atm.eject() # error no card



查看完整回答
反對 回復 2021-09-11
?
ITMISS

TA貢獻1871條經驗 獲得超8個贊

Atm不應該從AtmState但從無(或從object,無所謂)繼承。它應該只包含:state變量、change改變狀態AtmState的方法以及調用當前同名方法的方法中的每個方法,并state帶有一個名為例如atm包含調用Atm對象(上下文)的附加參數。

AtmState應該只包含沒有實現的方法(并且沒有變量),因為它是原始模式中的接口。對于 Python,您應該使其成為具有抽象方法的抽象類,請參閱模塊abc如何做到這一點。

派生自的具體類AtmState現在應該實現這些方法。通常每個類只需要一兩個方法,其余的應該只打印一個錯誤。例如,該NoCard.ejectCard()方法僅顯示無法彈出不存在的卡的錯誤。

通過從方法之一調用atm.change()方法(atm是由Atm類添加的附加參數),可以在狀態之間切換。


查看完整回答
反對 回復 2021-09-11
  • 2 回答
  • 0 關注
  • 261 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號