我在寻找什么样的设计模式以及如何在python中实现它

时间:2012-05-21 07:24:12

标签: python oop design-patterns

我试图为我的代码提供一些通用性。基本上我正在寻找的是这个。

我希望编写一个API接口MyAPI:

class MyAPI(object):
    def __init__(self):
       pass

    def upload(self):
       pass

    def download(self):
      pass

class MyAPIEx(object):
   def upload(self):
      #specific implementation

class MyAPIEx2(object): 
   def upload(self)
    #specific implementation

#Actual usage ... 
def use_api():
     obj = MyAPI()
     obj.upload()

所以我想要的是基于配置我应该能够调用上传功能
MyAPIEx或MyAPIEx2。我正在寻找的确切设计模式是什么,我如何在python中实现它。

2 个答案:

答案 0 :(得分:2)

您正在寻找Factory method(或任何其他工厂实施)。

答案 1 :(得分:1)

很难说你正在使用什么样的模式,没有更多的信息。实例化MyAPI的方法实际上就像@Darhazer提到的工厂一样,但听起来你更有兴趣知道用于MyAPI类层次结构的模式,而且没有更多信息我们不能说。

我在下面进行了一些代码改进,查找带有IMPROVEMENT一词的评论。

class MyAPI(object):
    def __init__(self):
       pass

    def upload(self):
       # IMPROVEMENT making this function abstract
       # This is how I do it, but you can find other ways searching on google
       raise NotImplementedError, "upload function not implemented"

    def download(self):
       # IMPROVEMENT making this function abstract
       # This is how I do it, but you can find other ways searching on google
       raise NotImplementedError, "download function not implemented"

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it
class MyAPIEx(MyAPI):
   def upload(self):
      #specific implementation

# IMPROVEMENT Notice that I changed object to MyAPI to inherit from it
class MyAPIEx2(MyAPI): 
   def upload(self)
      #specific implementation


# IMPROVEMENT changed use_api() to get_api(), which is a factory,
# call it to get the MyAPI implementation
def get_api(configDict):
     if 'MyAPIEx' in configDict:
         return MyAPIEx()
     elif 'MyAPIEx2' in configDict:
         return MyAPIEx2()
     else
         # some sort of an error

# Actual usage ... 
# IMPROVEMENT, create a config dictionary to be used in the factory
configDict = dict()
# fill in the config accordingly
obj = get_api(configDict)
obj.upload()