我正在尝试创建一个单例类,但它每次都会返回一个新实例。这是我的代码。
我犯了什么错吗?为什么每次都返回一个新实例?
我认为应该是一样的。
public final class SingletonA {
private static SingletonA instance;
private SingletonA(){
}
public static SingletonA getInstance() {
if(instance==null)
{
System.out.println("RETURNING NEW INSTANCE OF SingletonA Class");
return new SingletonA();
}
System.out.println("RETURNING OLD INSTANCE OF SingletonA Class");
return instance;
}
}
public class SingletonB {
public static void main(String[] args) {
SingletonA one = SingletonA.getInstance();
System.out.println("1."+one+" | "+one.hashCode());
SingletonA two = SingletonA.getInstance();
System.out.println("2."+two+" | "+two.hashCode());
SingletonA three = SingletonA.getInstance();
System.out.println("3."+three+" | "+three.hashCode());
}
}
// HERE IS THE OUTPUT
RETURNING NEW INSTANCE OF SingletonA Class
1.oop.singleton.SingletonA@2a139a55 | 705927765
RETURNING NEW INSTANCE OF SingletonA Class
2.oop.singleton.SingletonA@15db9742 | 366712642
RETURNING NEW INSTANCE OF SingletonA Class
3.oop.singleton.SingletonA@6d06d69c | 1829164700
答案 0 :(得分:2)
如下所示改变
if(instance==null) {
System.out.println("RETURNING NEW INSTANCE OF SingletonA Class");
instance = new SingletonA();
}
答案 1 :(得分:2)
您必须分配instance
否则检查将始终产生true,从而返回一个新实例:
public static SingletonA getInstance() {
if(instance==null)
{
System.out.println("CREATING NEW INSTANCE OF SingletonA Class");
instance = new SingletonA();
}
System.out.println("RETURNING INSTANCE OF SingletonA Class");
return instance;
}
答案 2 :(得分:2)
这里不正确,因为您正在返回SingletonA的新实例,并且永远不会将其分配给对象实例。
public static SingletonA getInstance() {
if(instance==null)
{
System.out.println("RETURNING NEW INSTANCE OF SingletonA Class");
return new SingletonA();
}
System.out.println("RETURNING OLD INSTANCE OF SingletonA Class");
return instance;
}
你的意思是肯定的
public static SingletonA getInstance() {
if(instance==null)
{
System.out.println("RETURNING NEW INSTANCE OF SingletonA Class");
instance = new SingletonA();
}
System.out.println("RETURNING OLD INSTANCE OF SingletonA Class");
return instance;
}
答案 3 :(得分:2)
您应该在返回测试中进行空检查之前将实例初始化为新的SingletonA()。
public final class SingletonA {
private static SingletonA instance;
private SingletonA(){
}
public static SingletonA getInstance() {
if(instance==null)
{
System.out.println("RETURNING NEW INSTANCE OF SingletonA Class");
// You are missing this assignment.
instance = new SingletonA();
return instance;
}
System.out.println("RETURNING OLD INSTANCE OF SingletonA Class");
return instance;
}
}