mardi 9 août 2022

How to properly design a solution, using patterns, that branches Trial and Pro version of an api?

I'm implementing some features that translate text and based on that my hobby app supports multiple types of translation (Bing, Google etc.). For that purpose, I created an abstract class

class Translate(ABC):
   @abstractmethod
   def translate(text, goal_lang):
      pass

Then I have

class GoogleTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class BingTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class YonigTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

I made a Facade for these classes in the following way:

class Google(GoogleTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

class Bing(BingTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

class Yoing(YonigTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

Why did I do it this way? Because I want to store another Google, Bing or Yonig features in one container and have Google features (for ex. meets, drive) stored in Google. However, the translator that I used is a free one and now I want to implement a pro (paid) version but still keep the old (free) one. When I decided to do it this way, I knew that it could get messy and that's why I came here to get some help and find the right approach. What I was thinking in doing is rename the GoogleTranslator to GoogleFreeTranslator and make another class that will be called GooglePaidTranslator(Translate). However, if I inherit both of these classes into Google and I call .translate(), I believe that the app will crash because both of the members that Google inherits from would have the same method! What I speak, translated to code would look like:

class GoogleFreeTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class GooglePaidTranslator(Translate):
    @staticmethod
    def translate(text, goal_lang):
        *translate logic*

class Google(GoogleFreeTranslator, GooglePaidTranslator):
    def __init__(self):
        pass

    def translate(self, text, goal_lang):
        return super().translate(text, goal_language)

This is where I'm stuck and I'm looking for help and further paths on how could I approach this. Should I maybe change the whole approach or is there a way to initialize Google and somehow tell the class to use the translate() method from one of the classes that it inherits from?

Aucun commentaire:

Enregistrer un commentaire