python - 以两种或多种方式连接到服务,在Python中委托(delegate)方法执行

标签 python python-3.x oop object inheritance

我遇到了一个有趣的案例,我必须根据消费者的偏好以两种不同的方式连接到 Web 服务。出于这个问题的目的,我不想提及任何产品,假设它是一个名为“Service”的 Web 服务,可以通过 RestAPI 和消息代理访问。

我的简化代码如下所示:

import configparser
import os

from MyApp.Exceptions import WrongModeException

class Service(object):
    cfg_file = 'path/to/cfg.ini'
    config = configparser.ConfigParser()
    config.read(cfg_file)

    @staticmethod
    def generate_password():
        return 'ToPsEcReTp4ssw0rD'

class ServiceAPI(Service):
    def __init__(self):
        self.connection = APIConnect(self.config.some_param)

    def do_stuff(self, a):
        self.connection.do_stuff(a=a)

class ServiceMessageBroker(Service):
    def __init__(self):
        self.connection = MessageBrokerConnect(self.config.some_param)

    def do_stuff(self, a):
        self.connection.do_stuff(a=a)

class ServiceWrapper(Service):
    def __init__(self):
        mode = self.config.get(option='mode')

        if mode == 'Message Broker':
            self.service = ServiceMessageBroker()
        elif mode == 'API':
            self.service = ServiceAPI()
        else:
            raise WrongModeException
            os.sys.exit(1)

    def do_stuff(self, **kwargs):
        self.service.do_stuff(**kwargs)


if __name__ == '__main__':
    s = ServiceWrapper()
    s.do_stuff(a='blabla')

有没有更好、更干净的方法来做到这一点?我正在考虑在字典中映射适当的函数,然后用它来执行,但对我来说似乎 super 难看。

提前致谢!

最佳答案

在我看来,使用字典作为函数调度程序是干净且适应性强的。与 if/elif/else 构造相比,我更喜欢它,特别是如果它有助于可读性。

例如,这对我来说似乎更具可读性:

class ServiceWrapper(Service):
    def __init__(self):
        mode = self.config.get(option='mode')

        d = {'Message Broker': ServiceMessageBroker,
             'API': ServiceAPI}

        if mode not in d:
            raise WrongModeException
            os.sys.exit(1)

        self.service = d[mode]()

    def do_stuff(self, **kwargs):
        self.service.do_stuff(**kwargs)

关于python - 以两种或多种方式连接到服务,在Python中委托(delegate)方法执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50349653/

相关文章:

python - django2.1 发送电子邮件失败 :ssl. SSLError : [SSL: WRONG_VERSION_NUMBER] wrong version number (_ssl. c:833)

python - 使用 Python 比较两个文件夹中的文件

python - 在电视节目中查看已删除邮件的文本或发件人

python - 实现所需的类层次结构行为的最佳方法

c# - 如何使用 XmlSerializer 序列化内部类?

python zeep,如何更容易地找到方法/属性所属的绑定(bind)?

python - FacetGrid 上的 Seaborn 颜色条用于具有标准化颜色映射的 histplot

python - 类内的 Numpy 数组赋值

python-3.x - 如何检查向量何时在 python 中转了一圈

java - 无法实现鼠标监听器