package com.mycontainer;

public class MyContainer {
    private static ContainerConfig cConfig;

    private MyContainer() {

    }

    public static ContainerConfig getConfiguration() {
        if (cConfig == null)
            cConfig = new ContainerConfig();
        return cConfig;
    }

}

最佳答案

我不得不说,这是延迟初始化和Singleton模式的较差的实现。没有同步,因此没有线程安全。在访问此代码的多个线程下,您可能会遇到多个实例。

更新:最好将您的代码如下所示:

package com.mycontainer;

public class MyContainer {
   // static final singleton object to rely on class loader to create it for you
   // in a thread safe way
   private static final ContainerConfig cConfig = new ContainerConfig();

   // private constructor to prevent instantiation
   private MyContainer() {}

   // getter method for your singleton object
   public static ContainerConfig getContainerConfig() {
      return cConfig;
   }
}

07-25 23:56