如何编写静态类持有者成语单身

时间:2017-11-21 09:00:40

标签: java singleton

我必须在延迟初始化中编写这段代码" static class holder idiom singleton"图案

 public class DateComparator{
    private static DateComparator instance = null;
    public static  DateComparator getInstance()
    {
       if(instance == null)
          instance = new DateComparator();
       return instance;
    }
 }

这是我更改的代码:

public class DateComparator{
    private static DateComparator container = null;
    private static class DateComparatorHolder {
        private static DateComparator instance=createInstance();
    }
    private static DateComparator createInstance() {
        if(container == null)
            //container = new DateComparator();
        return new DateComparator();
    }
    public static DateComparator getInstance()
    {       
        return DateComparatorHolder.instance;
    }

1 个答案:

答案 0 :(得分:1)

无需container变量或createInstance()

public class DateComparator{
    private static class DateComparatorHolder {
        private static final DateComparator instance= new DateComparator();
    }

    public static DateComparator getInstance()
    {       
        return DateComparatorHolder.instance;
    }
}

这就是全部。