2

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

我想写一个 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 中实现它。

4

2 回答 2

2

您正在寻找工厂方法(或工厂的任何其他实现)。

于 2012-05-21T07:27:51.793 回答
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()
于 2012-05-21T08:20:38.910 回答