'AbstractFactory pattern but some functions in ConcreteObjects are really the same
I am new in design patterns and wanted to do a simple AbstractFactory pattern in Python
My question would be, how should I handle some functions between two Concrete objects that are the same for now but could change in the future?
from abc import ABC, abstractmethod
class AbstractFactory(ABC):
@abstractmethod
def some_func(self):
pass
class ConcreteObject1(AbstractFactory):
def some_func(self, x, y):
return x + y
class ConcreteObject2(AbstractFactory):
def some_func(self, x, y):
return x + y
For now, some_func should really be implemented the same but could change in the future. Is it a good practice to design it like this even if they're the same now?
Solution 1:[1]
I think it would be OK if you handled it something like the following:
You can give the abstract method in the base class an implementation that derived class methods can call via super() to use some default definition. That way the method can stay abstract with a minimal amount of repetitive boilerplate code in each subclass. This is even noted in the abc.abstractmethod documentation at the end.
Seems like a reasonable way to do things if you think you might want to force subclasses to really implement it someday. You could even change the base class implementation to raise an exception if it's ever called should you decide to make writing one a requirement.
Here's what I mean:
from abc import ABC, abstractmethod
class AbstractFactory(ABC):
@abstractmethod
def some_func(self, x, y):
return x + y
class ConcreteFactory1(AbstractFactory):
def some_func(self, x, y):
return super().some_func(x, y)
class ConcreteFactory2(AbstractFactory):
def some_func(self, x, y):
return super().some_func(x, y)
if __name__ == '__main__':
obj1 = ConcreteFactory1()
print(obj1.some_func(1, 42)) # -> 43
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
