发现循环依赖的问题

时间:2016-05-25 18:24:39

标签: java oop design-patterns circular-dependency

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

每个模块都由一个单例表示,它实现了一个接口,为彼此提供了一些服务,抽象工厂提供它们,如下所示:

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 个答案:

答案 0 :(得分:1)

处理此问题的干净方法是使用依赖注入,以将依赖关系保持在接口级别。

UserMain可以依赖FilesInternaServiceFileMain可以依赖UserInternalService;但UserMain依赖FileMainFileMain依赖UserMain并不合适。换句话说,依靠具体实施是不可能的。

FilesInternaService的实例应注入UserMainUserInternalService的实例应注入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