如何确保只创建一个单例类的实例?

时间:2015-10-23 16:57:12

标签: singleton

我已经阅读过Singleton设计模式的概念,并且理解为了制作类单例,我们必须执行以下步骤:

1)私有构造函数,用于限制其他类的实例化。

2)同一个类的私有静态变量,它是该类的唯一实例。

3)返回类实例的公共静态方法,这是外部世界获取单例类实例的全局访问点。

所以我的班级看起来像这样:

public class Singleton {

   private static Singleton singleton =new Singleton();;

   /* A private Constructor prevents any other 
    * class from instantiating.
    */
   private Singleton(){ 
       System.out.println("Creating new now");
   }

   /* Static 'instance' method */
   public static Singleton getInstance( ) {
     return singleton;
   }
   /* Other methods protected by singleton-ness */
   public void demoMethod( ) {
      System.out.println("demoMethod for singleton"); 
   }
}

但是在这里我们如何才能确保只创建一个Singleton实例?假设我有2个类Singletondemo1和Singletondemo2。 在Singletondemo1中,我调用了getInstance()并创建了一个对象。我也可以在Singletondemo2中这样做。

那么我们将如何确保只创建对象并且它也是线程安全的。

0 个答案:

没有答案