its a question mainly about design.
Lets suppose we have a class that has the role of initiating different subclasses of a certain type. The problem comes when the __init__
method receives different parameter for each subtype. Is there any way to avoid the if
's inside the function that initializers the classes just to know what parameters to pass in? Maybe some design pattern that I am not aware of. Or is it an outcome of a bad design?
below is an example of what I mean. notice the manage
static method that has the if...else...
in it and if there were more types of workers, we would have more if
's, which is what I am trying to avoid.
from abc import ABCMeta
class BaseWorker(metaclass=ABCMeta):
def work(self):
pass
class Worker1(BaseWorker):
def __init__(self, name):
self.name = name
def work(self):
pass
class Worker2(BaseWorker):
def __init__(self, name, age):
self.name = name
self.age = age
def work(self):
pass
class Manager(object):
@staticmethod
def manage(workers:[BaseWorker]):
for worker in workers:
if worker.__name__ == Worker1.__name__:
w = worker(name="davay")
w.work()
else:
worker(name="ok", age="55")
if __name__ == '__main__':
workers = [Worker1, Worker2, Worker1]
Manager.manage(workers)
Thanks!
Aucun commentaire:
Enregistrer un commentaire