Singleton模式是創(chuàng)建模式。
這種模式只涉及一個類是負(fù)責(zé)創(chuàng)建自己的對象。
該類確保只有一個對象獲得創(chuàng)建。
這個類提供了一種方法來訪問它的唯一對象。
例如,當(dāng)設(shè)計一個用戶界面,我們只能有一個主應(yīng)用程序的窗口。我們可以使用Singleton模式,以確保有是MainApplicationWindow對象的一個實例。
下面的代碼將創(chuàng)建一個主窗口類。
MainWindow類有其私有的構(gòu)造,并有其自身的靜態(tài)實例。
主窗口類提供了一個靜態(tài)方法來獲取其靜態(tài)實例外面的世界。
我們的演示類將使用主窗口類來獲得一個主窗口對象。
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(); }}感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答
圖片精選