Java 单例模式
Java设计模式 - 单例模式
单例模式是一种创建模式。
这种模式只涉及一个单独的类,它负责创建自己的对象。
该类确保只创建单个对象。
这个类提供了一种访问其唯一对象的方法。
例如,当设计一个用户界面时,我们可能只有一个主应用程序窗口。我们可以使用Singleton模式来确保只有一个MainApplicationWindow对象的实例。
例子
下面的代码将创建一个MainWindow类。
MainWindow类的构造函数是私有的,并且有一个自身的静态实例。
MainWindow类提供了一个静态方法来获取它的静态实例到外部世界。
Main,我们的演示类将使用MainWindow类来获取一个MainWindow对象。
class MainWindow {
   //create an object of MainWindow
   private static MainWindow instance = new MainWindow();
   //make the constructor private so that this class cannot be
   //instantiated by other class
   private MainWindow(){}
   //Get the only object available
   public static MainWindow getInstance(){
      return instance;
   }
   public void showMessage(){
      System.out.println("Hello World!");
   }
}
public class Main {
   public static void main(String[] args) {
      //Get the only object available
      MainWindow object = MainWindow.getInstance();
      //show the message
      object.showMessage();
   }
}
上面的代码生成以下结果。
Hello World!