jeudi 30 novembre 2017

dynamically choose API to use

I use an external tool in my Python code. In order to initialize this tool, I have to create a couple of objects. The external tool in question provides two quite different APIs, and no one of these APIs is capable of creating all objects the tool needs. Let's say, the tool is trafic simulation tool, where car objects are created using API 1 and bikes are created using API 2.

I have played with inheritance, tried to pick an appropriate design pattern but all my solutions look ugly to me.

The most simple way to represent what I am trying to achieve is:

class ObjectHandler():    
    api_1_types = ('type1', 'foo')
    api_2_types = ('type2', 'bar')

    def __init__(self):
        self.handler1 = ObjectHandler1()
        self.handler2 = ObjectHandler2()

    def create(self, obj_type):
        if obj_type in self.api_1_types:
            return self.handler1.create()
        elif obj_type in self.api_2_types:
            return self.handler2.create()
        else:
            raise NotImplementedError

class ObjectHandler1():
    def __init__(self):
        # load external module that defines API 1
    def create(self):
        # return an object created via API 1

class ObjectHandler2():
    def __init__(self):
        # load external module that defines API 2
    def create(self):
        # return an object created via API 2

if __name__ == '__main__':
    handler = ObjectHandler()
    object_1 = handler.create('type1')  # must be created by ObjectHandler1
    object_2 = handler.create('type2')  # must be created by ObjectHandler2

I am now searching for a good OO and pythonic way to achieve this.

Aucun commentaire:

Enregistrer un commentaire