//SingletonObject.java

package Test;

public class SingletonObject {

    private SingletonObject() {

    }

    private static SingletonObject instance = new SingletonObject();
    private static SingletonObject instance1 = new SingletonObject();

    public static SingletonObject getInstance(){
        return instance;

    }

    public static SingletonObject getInstance1(){
        return instance1;
    }

    public void showMessage(){
        System.out.println("Hello World !!! ");
    }

    public void dispMsg(){
        System.out.println("Hai");
    }

}

//SingletonObjectDemo.java

package Test;

public class SingletonObjectDemo {
    public static void main(String[] args){

        //SingletonObject obj = new SingletonObject();

        SingletonObject obj = SingletonObject.getInstance();
        obj.showMessage();

        SingletonObject obj1 = SingletonObject.getInstance1();
        obj1.showMessage();
        obj1.dispMsg();

    }

}

最佳答案

实现单例的几种方法是我通常使用的一种方法是:

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

}


并将您的默认构造函数设为私有:

private SingletonObject()
{
  //optional code
}


有了这个,您可以确保仅返回SingletonObject的一个实例

10-05 18:35