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

2024-05-29 11:54:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图给我的代码一点通用性。基本上我要找的就是这个。你知道吗

我想写一个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()

所以我想要的是,根据配置,我应该能够调用upload函数
MyAPIEx或MyAPIEx2。我要寻找的确切设计模式是什么,以及如何在python中实现它。你知道吗


Tags: 代码selfapiobjobjectdefpassimplementation
2条回答

如果没有更多的信息,很难说你在使用什么模式。实例化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()

您正在寻找Factory method(或工厂的任何其他实现)。你知道吗

相关问题 更多 >

    热门问题