如何创建一对一的单例关系



我的应用程序中有两个单例,这是我的问题:它们中的每一个都需要彼此,所以我无法构建两者中的任何一个,因为我会得到一个堆栈溢出错误。如何克服它?

public class ApplicationService {
    private ApplicationDao applicationDao;
    private DerogationService derogationService;
    private LogService logService;
    private static ApplicationService applicationServiceInstance;
    private ApplicationService() 
    {
        applicationDao = ApplicationDao.getInstance();
        derogationService = DerogationService.getInstance();
        logService = LogService.getInstance();
    }
    public static synchronized ApplicationService getInstance(){
        if(applicationServiceInstance == null)
        {
            applicationServiceInstance = new ApplicationService();
        }
        return applicationServiceInstance;
    }

.

public class DerogationService {
    private DerogationDao derogationDao;
    private ApplicationService applicationService;
    private DroitService droitService;
    private static DerogationService derogationServiceInstance;
    private DerogationService(){
        applicationService = ApplicationService.getInstance();
        droitService =  DroitService.getInstance();
        derogationDao = DerogationDao.getInstance();
    }
    public static synchronized DerogationService getInstance(){
        if(derogationServiceInstance == null)
        {
            derogationServiceInstance = new DerogationService();
        }
        return derogationServiceInstance;
    }

谢谢伙计们! :)

正如您在 OP 中声明而没有实际说出来的那样,您遇到了循环引用问题。

您可以考虑使用 Spring 容器(以及其他容器)来解决此问题。

我已经找到了方法。

public class ApplicationService {
    private ApplicationDao applicationDao;
    private DerogationService derogationService;
    private LogService logService;
    private static ApplicationService applicationServiceInstance;
    private ApplicationService() 
    {
        applicationDao = ApplicationDao.getInstance();
        //I don't do it there 
        //derogationService = DerogationService.getInstance();
        logService = LogService.getInstance();
    }
    public static synchronized ApplicationService getInstance(){
        if(applicationServiceInstance == null)
        {
            applicationServiceInstance = new ApplicationService();
            // But here, so i won't get this loop problem.
            applicationServiceInstance.derogationService = DerogationService.getInstance();
        }
        return applicationServiceInstance;
    }

感谢那个给我一个想法的人,即使他刚刚删除了他的帖子......并感谢所有答案

最新更新