我正在设计一个系统,其中有两个模块,一个用于管理文件,另一个用于用户。对于某些逻辑运算,它们需要彼此提供的服务。
每个模块都由一个单例表示,该单例实现一个相互提供一些服务的接口,并通过抽象工厂来提供它们,如下所示:
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();
}
}
我不完全确定我是否正确处理了循环依赖。
有什么办法可能会意外中断吗?
EDIT:正如下面已经回答的那样,处理这个问题的正确方法是注入。然而,处理这个问题的正确方法不是我在这里问的,而是这个特定的解决方案如何崩溃。
处理此问题的简洁方法是使用依赖项注入,将依赖项保留在接口级别。
没关系UserMain
依赖FilesInternaService
没关系FileMain
依赖UserInternalService
;但这不行UserMain
依赖FileMain
or for FileMain
依赖UserMain
。也就是说,不能依赖于具体的实现。
一个实例FilesInternaService
应注入UserMain
和一个实例UserInternalService
应注入FileMain
.
参考
- 循环依赖是否被认为是糟糕的设计? https://stackoverflow.com/questions/9173494/are-circular-dependencies-considered-bad-design
- 为什么循环引用被认为是有害的? https://stackoverflow.com/questions/1897537/why-are-circular-references-considered-harmful
- https://softwareengineering.stackexchange.com/questions/11856/whats-wrong-with-circular-references https://softwareengineering.stackexchange.com/questions/11856/whats-wrong-with-circular-references
- https://softwareengineering.stackexchange.com/questions/306483/how-to-solve-circular-dependency https://softwareengineering.stackexchange.com/questions/306483/how-to-solve-circular-dependency
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)