gpt4 book ai didi

java - 如何编写静态类持有者习惯用法单例

转载 作者:行者123 更新时间:2023-12-02 11:58:47 25 4
gpt4 key购买 nike

我必须以延迟初始化“静态类持有者习语单例”模式编写此代码

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

仅此而已。

关于java - 如何编写静态类持有者习惯用法单例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47409035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com