簡體   English   中英

抽象工廠設計模式的實現

[英]Abstract Factory Design pattern implementation

我要以OOP方式重寫我已經在使用的Python代碼,因為我想以模塊化的方式實現它。 我有一個使用多個參數獲得的數據集。 我想實現一個抽象工廠模式,並用它實例化包含不同參數的不同數據集的不同對象。 最終目標是使用兩個不同的數據集,我可以計算特定的內容,而且我不知道如何實現適用於兩個具體對象的方法。

在我共享的圖像中,既可以看到抽象工廠方法,又可以看到兩個名為FompyDatasetHigh和FompyDatasetLow的具體數據集(我知道UML不是正確的,而只是顯示結構)。 然后,我想實現一種稱為Dibl的方法,該方法將兩個數據集都作為參數並返回計算。 我理解的Abstract Factory方法的實現是在我迷路的方法中實現的。

那么如何編寫一個將兩個具體工廠對象作為參數的方法

我希望我所提供的信息足夠多,如果可以,我可以嘗試提供其他信息。

如果希望對象具有抽象類中的方法,則您的具體類需要繼承抽象類

# Abstract Builder
class MonsterBuilder:
    def __init__(self):
        self.give_description()
        self.give_equipment()

    def give_description(self):
        raise NotImplementedError

    def give_equipment(self):
        raise NotImplementedError

    def __repr__(self):
        return "{0.description} | Wielding: {0.equipment}".format(self)


# Concrete Builder
class Orc(MonsterBuilder):
    descriptions = [" hungry", "n ugly", "n evil"]

    def give_description(self):
        description = random.choice(self.descriptions)
        self.description = "A{} Orc".format(description)

    def give_equipment(self):
        self.equipment = "blunt sword"

其他選項可能依賴於將參數傳遞給類:

def create_orc(weapon):

    class Orc(MonsterBuilder):
        descriptions = [" hungry", "n ugly", "n evil"]

        def give_description(self):
            description = random.choice(self.descriptions)
            self.description = "A{} Orc".format(description)

        def give_equipment(self):
            self.equipment = "blunt {}".format(weapon)

    return Orc()

orc_1 = create_orc('knife')
print(orc_1)
# >>> A hungry Orc | Wielding: blunt knife

orc_2 = create_orc('hammer')
print(orc_1)
# >>> An ugly Orc | Wielding: blunt hammer

此回購中有一些很棒的python OOP模式示例: https : //github.com/faif/python-patterns

我還建議您在進入OOP之前先閱讀他們的用例,如果使用不當,可能會使您的代碼難以閱讀。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM