Gabriel Esp
Gabriel Esp

Reputation: 47

Abstract Factory Design pattern implementation

I am rewriting my already working Python code in a OOP manner as I want to implement it in a modular way. I have a dataset that has been obtained using several parameters. I want to implement an Abstract Factory Pattern and with that instantiate different objects containing different datasets with different parameters. The ultimate goal is that with two different datasets I can calculate specific stuff and I don't know how to implement a method that applies to both concrete objects.

In the image that I'm sharing it can be seen both the abstract factory method and two concrete datasets called FompyDatasetHigh and FompyDatasetLow (I know the UML is not right but its only to show the structure). Then I want to implement a method called Dibl that takes as a argument both datasets and returns a calculation. The implementation of the Abstract Factory method I understand, is at the method where I get lost.

So how would you write a method that takes as a argument both Concrete Factory Objects

I hope the information I've given its enough if not I can try to provide something else.

Upvotes: 0

Views: 835

Answers (1)

s3bw
s3bw

Reputation: 3049

If you want your objects to have a method from your abstract class, your concrete classes need to inherit the abstract class

# 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"

Other option could rely on passing arguments to a class:

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

There are some great examples of OOP patterns in python in this repo: https://github.com/faif/python-patterns

I'd also suggest reading their use cases before jumping into OOP, it's likely to make your code harder to read if not used appropriately.

Upvotes: 1

Related Questions