Singleton模式是创建模式。

这种模式只涉及一个类是负责创建自己的对象。

该类确保只有一个对象获得创建。

这个类提供了一种方法来访问它的唯一对象。

例如,当设计一个用户界面,我们只能有一个主应用程序的窗口。我们可以使用Singleton模式,以确保有是MainApplicationWindow对象的一个​​实例。

下面的代码将创建一个主窗口类。

MainWindow类有其私有的构造,并有其自身的静态实例。

主窗口类提供了一个静态方法来获取其静态实例外面的世界。

我们的演示类将使用主窗口类来获得一个主窗口对象。

class MainWindow {
   //create an   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   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   available
      MainWindow   = MainWindow.getInstance();

      //show the message
       .showMessage();
   }
}

 

收藏 打印