I've got into some interesting design question.
I have some abstract class, Let's Name it ServiceClass
Let's say I have 2 subclasses, Named CoolServiceClass
and AmazingServiceClass
, both inheriting from ServiceClass
.
class ServiceClass(ABC):
@abstractmethod
def do_something(self):
pass
class CoolServiceClass(ServiceClass):
def do_something(self):
return 'Cool!'
def do_nothing(self):
return 'Nothing!'
class AmazingServiceClass(ServiceClass):
def do_something(self):
return 'Amazing!'
def just_do_it(self):
return 'Nope'
I want to write the client code but I don't want it to be coupled to one of the sub-classes in the client code. I don't want the client code to be able to use any of the methods just_do_it
or do_nothing
, so I'll be able to replace between their implementations easily. I know that python is duck-typed language but I still wonder what is the proper way to handle this situation?
One solution I thought of is using some kind of proxy class that looks something like this:
class ProxyServiceClass(ServiceClass):
def __init__(self, service_class):
self.service_class = service_class
def do_something(self):
return self.service_class.do_something()
And then the client code will look like this:
service_class1 = ProxyServiceClass(CoolServiceClass())
service_class2 = ProxyServiceClass(AmazingServiceClass())
Now, if I'll try to use any of the methods just_do_it
or do_nothing
I'll get an exception.
I am a little bit skeptic about this solution because I haven't seen similar solutions, I'll be happy to hear your opinions.
Thanks!