首页 > 解决方案 > 跨多个模块使用外观模式时如何避免循环依赖

问题描述

我正在尝试实现一个外观模式来访问两种不同的文件类型,但我一直遇到循环依赖。这是常见的,如果是这样,避免它的标准方法是什么?

我在单独的模块中有两种文件类型(A 和 B),它们由另一个单独interface.py模块中的外观访问。外观模块需要从每个模块导入 FileType 类以返回对象,并且还实现了一个方法determine_file_type(path)和一个自定义错误类IncorrectFileType

我现在希望向add_data_from_another_fileFileTypeA 添加一个方法。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 模式的经典使用,那么我在这里缺少的明显技巧是什么?

标签: pythondesign-patterns

解决方案


推荐阅读