我来自Java背景,我想知道如何在python中实现类似于SPI模式的东西:How to implement the API/SPI Pattern in Java?。
基本上,我们正在构建一个平台,我们希望将SDK/API包分发给将在平台之上构建数据管道的“平台用户”。
我们只想共享接口,实际的实现在运行时由平台解决。
例如,在平台用户共享SDK类/接口之后,在运行时,当他们的代码调用IEventLog.send_event()方法时,平台将使用kafka生成器将事件发送到Kafka。
class IEventLog(object):
def __init__(self):
pass
def send_event(self,qn,corrId):
raise Exception("Error Runtime feature")发布于 2021-05-19 20:33:18
如果我正确理解了您的需求,第一种方法可以使用如下所示的动态导入:
# set target module somehow, for example via environment variable
# or some kind of settings file.
import os
import imporlib
class EventLog(object):
def __init__(self):
impl_module = os.environ.get("IMPL_MODULE")
self.impl = importlib.import_module(imp_module)
def send_event(self,qn,corr_id):
self.impl.send_event(qn, corr_id)二是使用策略模式。
class EventLog(object):
def __init__(self):
self.impl = None
def set_impl(self, impl):
self.impl = impl
def send_event(self,qn,corr_id):
self.impl.send_event(qn, corr_id)第三种是使用某种依赖注入。
https://stackoverflow.com/questions/67467137
复制相似问题