【发布时间】:2021-11-04 18:04:39
【问题描述】:
我有以下代码:
package DesignPatterns;
public class SingletonProblem
{
public static void main(String[] args) {
System.out.println(BillPughSingleton.getInstance());
System.out.println(BillPughSingletonWithoutContainer.getInstance());
}
}
class BillPughSingletonWithoutContainer
{
private static BillPughSingletonWithoutContainer instance = new BillPughSingletonWithoutContainer();
static {
System.out.println("Static is now loaded in BillPughSingletonWithoutContainer");
}
private BillPughSingletonWithoutContainer() {}
public static BillPughSingletonWithoutContainer getInstance()
{
return instance;
}
}
class BillPughSingleton
{
private static class Container
{
public static BillPughSingleton instance = new BillPughSingleton();
}
private BillPughSingleton() {}
public static BillPughSingleton getInstance()
{
return Container.instance;
}
}
输出是:
DesignPatterns.BillPughSingleton@36baf30c
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
如果在没有容器的示例中,当调用 BillPughSingletonWithoutContainer.getInstance() 时实例似乎也被延迟加载,为什么容器有用?
在热切加载(BillPughSingletonWithoutContainer 声称是什么)时,我预计输出是:
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingleton@36baf30c
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
代替:
DesignPatterns.BillPughSingleton@36baf30c
Static is now loaded in BillPughSingletonWithoutContainer
DesignPatterns.BillPughSingletonWithoutContainer@5ca881b5
那么换句话说,使用容器有什么好处(在 Java 中)?
【问题讨论】:
-
线程安全,一般来说。
-
所以 BillPughSingletonWithoutContainer 不是线程安全的?你能在答案中解释一下吗,因为我不明白这个:)。
-
它是完全线程安全的,只是不 lazy。 Pugh 模式是一种延迟加载静态实例的安全/高效方式
-
好的,你能在答案中展示 BillPughSingletonWithoutContainer 是如何不延迟加载的吗?
-
您的第一个例子不是 Bill Pugh Singleton。根据定义,Bill Pugh Singleton 使用嵌套类。
标签: java