gpt4 book ai didi

java - 发现循环依赖问题

转载 作者:行者123 更新时间:2023-12-01 09:53:21 25 4
gpt4 key购买 nike

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

每个模块都由一个单例表示,该单例实现一个相互提供一些服务的接口(interface),并通过抽象工厂来提供它们,如下所示:

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();
}
}

我不确定我是否正确处理了循环依赖。有什么办法可能会意外中断吗?

编辑:正如下面已经回答的那样,处理这个问题的正确方法是注入(inject)。然而,处理这个问题的正确方法不是我在这里问的,而是这个特定的解决方案如何崩溃。

最佳答案

处理此问题的简洁方法是使用依赖项注入(inject),将依赖项保留在接口(interface)级别。

UserMain 可以依赖 FilesInternaServiceFileMain 也可以依赖 UserInternalService;但 UserMain 不能依赖 FileMainFileMain 依赖 UserMain。换句话说,依赖具体实现是不行的。

FilesInternaService 的实例应注入(inject)到 UserMain 中,UserInternalService 的实例应注入(inject)到 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

关于java - 发现循环依赖问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37444940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com