简体   繁体   English

静态字段和单例的麻烦

[英]Trouble with static field and singleton

I have two classes: 我有两节课:

public class Singleton{
    private Singleton(){...}

    private static class InstanceHolder{
        private static final Singleton instance=new Singleton();
    }

    public static Singleton getInstance(){
        return InstanceHolder.instance;
    }
}

and

public class Someclass{
    private static final Singleton singleton=Singleton.getInstance();

    public static Singleton getSingleton(){
        return singleton;
    }
}

Problem 问题

If somewhere (actually, in another singleton-class constructor) I use something like this: 如果在某个地方(实际上,在另一个单例类构造函数中)我使用这样的东西:

private final Singleton singleton=Someclass.getSingleton();

my singleton always null 我的singleton总是空的

Question Why? 问题为什么?

Your example works fine, thus it's incomplete. 你的例子工作正常,因此它不完整。

Perhaps in your real application you have a dependecy cycle between your classes, so that getSingleton() is invoked before initialization of Someclass is completed, something like the following, but with multiple classes involved: 也许在您的实际应用程序中,您的类之间有一个依赖循环,因此在完成Someclass初始化之前调用getSingleton() ,类似于以下内容,但涉及多个类:

public class Foo {
    private static Foo INSTANCE = new Foo(); // Prints null
    private static String s = "foo";

    public Foo() {
        System.out.println(s);
    }
}

It's especially likely if you have multiple interdependent singletons implemented this way. 如果您以这种方式实现多个相互依赖的单身,那么这种情况尤其可能。 Try to find and elmininate these cycles. 尝试找到并消除这些周期。

Also, perhaps it would be better to use some kind of DI or Service Locator pattern instead of implementing singleton behaviour manually. 此外,也许最好使用某种DI或服务定位器模式而不是手动实现单例行为。

You should create the singleton instance on the first call to getInstance() rather than statically. 您应该在第一次调用getInstance()而不是静态时创建单例实例。 This will work regardless of dependency cycles. 无论依赖循环如何,这都将起作用。

public class Singleton {
  private static Singleton instance = null;

  private Singleton(){...}

  public static Singleton getInstance() {
    if(instance == null) {
      instance = new Singleton();
    }
    return instance;
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM