有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java发现了循环依赖的问题

我正在设计一个系统,其中有两个模块,一个是手势文件,另一个是用户。对于某些逻辑操作,它们需要彼此提供的服务

每个模块都由一个单独的模块表示,该模块实现了一个相互提供一些服务的接口,抽象工厂提供这些服务,如下所示:

public class UserMain implements UserInternalService {

/*
 * Internal interfaces
 */
/**
 * Allows interaction with the projects database.
 */
FilesInternaService fileSystem;

/**
 * Constructor is private, as this is a singleton.
 */
protected UserMain() {
}

private static UserMain singleton = null;

/**
 * Singleton factory. Returns a reference to the singleton. If there is no
 * reference yet, creates it.
 */
protected static synchronized UserMain getReference() {
    if (singleton == null) {
        singleton = new UserMain();
        singleton.fileSystem = FileMain.getInternalService();
    }
    return singleton;
}

/**
 * Factory method for the singleton as a UserInternalService
 */
public static UserInternalService getUserInternalService() {
    return getReference();
}

}

文件模块主类如下所示:

public class FileMain implements FilesInternaService{

/**
 * Interface to user subsystem for request validation, etc.
 */
UserInternalService userSystem;

/**
 * Creation of instances aside from singleton disallowed.
 */
protected FileMain(){};

private static FileMain singleton = null;

/**
 * Singleton factory.
 * Returns a reference to the singleton.
 * If there is no reference yet, creates it.
 */
protected synchronized static FileMain getReference(){
    if(singleton == null)
        singleton = new FileMain();
        singleton.userSystem = UserMain.getUserInternalService();
    return singleton;
}

/**
 * Abstract factory for Internal Services singleton.
 * @return
 */
public static FilesInternaService getInternalService(){
    return getReference();
}
}

我不确定我是否正确处理了循环依赖关系。 有没有可能会意外破裂

编辑:正如下面所回答的,正确的处理方法是注射。然而,正确的处理方法并不是我在这里要问的问题,而是这个具体的解决方案会如何爆发


共 (1) 个答案

  1. # 1 楼答案

    处理这个问题的干净方法是使用依赖项注入,将依赖项保持在接口级别

    UserMain依赖FilesInternaService是可以的,对FileMain依赖UserInternalService也是可以的;但是UserMain依赖FileMain或者FileMain依赖UserMain是不好的。换句话说,依靠具体的实施是不行的

    一个FilesInternaService的实例应该被注入UserMain,一个UserInternalService的实例应该被注入FileMain


    参考资料

    1. Are circular dependencies considered bad design?
    2. Why are circular references considered harmful?
    3. https://softwareengineering.stackexchange.com/questions/11856/whats-wrong-with-circular-references
    4. https://softwareengineering.stackexchange.com/questions/306483/how-to-solve-circular-dependency