我必须以惰性初始化“静态类持有人惯用语单例”模式编写此代码

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

最佳答案

不需要container变量或createInstance()

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

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


就这样。

07-25 23:35