python - 跨多个模块使用外观模式时如何避免循环依赖
问题描述
我正在尝试实现一个外观模式来访问两种不同的文件类型,但我一直遇到循环依赖。这是常见的,如果是这样,避免它的标准方法是什么?
我在单独的模块中有两种文件类型(A 和 B),它们由另一个单独interface.py
模块中的外观访问。外观模块需要从每个模块导入 FileType 类以返回对象,并且还实现了一个方法determine_file_type(path)
和一个自定义错误类IncorrectFileType
。
我现在希望向add_data_from_another_file
FileTypeA 添加一个方法。interface.determine_file_type
它需要做的第一件事是确定它从什么类型的文件添加数据,但是如果不创建循环依赖项,它就无法访问该方法。出于同样的原因,我也无法IncorrectFileType
从任一模块中引发错误。file_type_a,b
## Module: interface.py
from file_type_a import FileTypeA
from file_type_b import FileTypeB
def get_file(path):
if determine_type(path) == "typeA":
return FileTypeA(path)
elif determine_type(path) == "typeB":
return FileTypeB(path)
def determine_file_type(path):
...
return file_type
class IncorrectFileTypeError(ValueError):
pass
## Module: file_type_a.py
class FileTypeA():
def add_data_from_another_file(self, path):
file_type = determine_file_type(path) ### CAN'T IMPORT THIS
if file_type == "typeB":
raise IncorrectFileTypeError() ### CAN'T IMPORT THIS
## Module: file_type_b.py
class FileTypeB():
pass
一种解决方案可能是将 实现determine_file_type
为类的静态方法,AbstractFileType
但如果我需要在其中一个具体类中引发异常,这对我没有帮助。(在我的真实示例中也感觉它可能很混乱,但这可能是一个单独的问题!)
这感觉像是对 Facade 模式的经典使用,那么我在这里缺少的明显技巧是什么?
解决方案
推荐阅读
- javascript - 正则表达式匹配 Javascript 中的版本号
- python - 如何使用 Jinja2 单独访问字典列表中的每个字典?
- substrate - Parity Substrate - 区块尚未最终确定
- html - 是否可以使用 Bootstrap 4 将 div 折叠到左侧,而不是 div 折叠到顶部?(动画)
- vue.js - 未捕获的 ReferenceError:显示表格时未定义 Vue
- python - BeautifulSoup4 如何检查标签是否有特定的子标签
- java - 来自 Java 错误 NoHostAvailableException 的 Datastax Cassandra SSL 连接
- typescript - 如何让 TypeScript 对扩展从“节点模块”导入的类感到满意?
- javascript - 是否可以将 github 网页连接到 SQL 数据库?
- python - 数据集不适合 LSTM 训练的内存