java Signleton模式詳解及範例程式碼_java

來源:互聯網
上載者:User

Singleton模式是建立模式。

這種模式只涉及一個類是負責建立自己的對象。

該類確保只有一個對象獲得建立。

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

例如,當設計一個使用者介面,我們只能有一個主應用程式的視窗。我們可以使用Singleton模式,以確保有是MainApplicationWindow對象的一個​​執行個體。

下面的代碼將建立一個主視窗類。

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

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.