亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

java Signleton模式詳解及示例代碼

 更新時間:2016年10月08日 08:32:11   投稿:lqh  
Singleton模式是創(chuàng)建模式。這種模式只涉及一個類是負(fù)責(zé)創(chuàng)建自己的對象。該類確保只有一個對象獲得創(chuàng)建。這個類提供了一種方法來訪問它的唯一對象

Singleton模式是創(chuàng)建模式。

這種模式只涉及一個類是負(fù)責(zé)創(chuàng)建自己的對象。

該類確保只有一個對象獲得創(chuàng)建。

這個類提供了一種方法來訪問它的唯一對象。

例如,當(dāng)設(shè)計一個用戶界面,我們只能有一個主應(yīng)用程序的窗口。我們可以使用Singleton模式,以確保有是MainApplicationWindow對象的一個​​實(shí)例。

下面的代碼將創(chuàng)建一個主窗口類。

MainWindow類有其私有的構(gòu)造,并有其自身的靜態(tài)實(shí)例。

主窗口類提供了一個靜態(tài)方法來獲取其靜態(tài)實(shí)例外面的世界。

我們的演示類將使用主窗口類來獲得一個主窗口對象。

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();
  }
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

相關(guān)文章

最新評論