jeudi 1 août 2019

Design pattern for inheriting across modules

I have a BaseClass object with two ChildClass objects inheriting from it. Each of these is a significant bit of code (>1000 lines) and they each have their own module. So the structure is as follows:

Module 1 with BaseClass

from abc import ABCMeta

class BaseClass(metaclass=ABCMeta):

Module 2 with ChildClass 1

from module1 import BaseClass

class ChildClass1(BaseClass):

Module 3 with ChildClass 2

from module1 import BaseClass

class ChildClass2(BaseClass):

At the moment I am using (I think) a Factory Design Pattern, where I have a function in a separate module controlling which ChildClass is called:

Module 4 with Class Controller

from module2 import ChildClass1
from module3 import ChildClass2

def controller():
    if condition:
        return ChildClass1()
    else:
        return ChildClass2()

I can't put this function in Module 1 because I will end up with circular imports so currently it is sitting in its own module.

A previous version of the code had the controller as a staticmethod to the BaseClass in Module 1 with the import ChildClass statements within the staticmethod, but I didn't like that pattern so I changed it to the current structure.

My question is - Is there a better design pattern that I can use without having to put everything in the same module?

Aucun commentaire:

Enregistrer un commentaire