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

How to create a one to one singleton relation

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

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

感谢给我一个想法的人,即使他在之后删除了他的 post。 感谢所有的答案