gpt4 book ai didi

java - 单例类中成员的不同实例化

转载 作者:行者123 更新时间:2023-11-30 09:07:47 24 4
gpt4 key购买 nike

正如标题所说,这之间有什么区别吗:

    public final class Foo {

private static final Foo foo;

private final ArrayList<String> text = new ArrayList<String>();
//other members
public static Foo getFooInstance(){
if(foo == null)
{
foo = new Foo();
}
return foo;
}
public ArrayList<String> getList(){
return text;
}

 public final class Foo {

private static final Foo foo = new Foo();
private final ArrayList<String> text;
private Foo(){
//other members
text = new ArrayList<String>();
}

public static Foo getFooInstance(){
return foo;
}
public ArrayList<String> getList(){
return text;
}

我认为没有区别,更清楚地说,我发布了这个问题。

最佳答案

如何初始化最终的实例成员?

这两种方法都是 final 变量在构造函数中或在声明本身时对其进行初始化的有效方法。

您可以使用另一种方法在 initialization block 中初始化最终实例变量。

示例代码:

public final class Foo {

private final ArrayList<String> text;

// initialization block
{
text = new ArrayList<String>();
}

}

单例设计模式

SingletonGang of Four 的一部分设计模式,它被归类在创 build 计模式下。

  • 您的第一个解决方案是使用惰性初始化 单例模式。使用双重检查锁定单例模式使其线程安全。

  • 您的第二个解决方案在多线程的情况下更安全,其中实例在声明本身时被初始化。

在这里阅读更多信息 Singleton Design Pattern – An Introspection w/ Best Practices

关于java - 单例类中成员的不同实例化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23843934/

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