單例設計模式(Singleton Class)
看看例子,并閱讀代碼行的注釋更清楚。這是java代碼,你可以使用C ++和.net編程使用相同的過程。123456789101112131415161718192021222324252627282930313233 | public class SingletonDemo{ //Make the constructor private, so no other call can create object of //this class directly using new operator. private SingletonDemo (){} /*Create a private member variable of same class type(SingletonDemo Class here), so that we can store the single object value in this variable and maintain it throughout the application life time*/ private static SingletonDemo objSingletonDemo; /*Create a static method to access from other classes which returns the existing objects reference. Check the null values of the object as below code, and if it is null then create the object for the first time only and return it. If it is not null, then just return the previous value.*/ public static SingletonDemo getInstance() { if(null == objSingletonDemo) { objSingletonDemo = new SingletonDemo(); } return objSingletonDemo; } public void testFun() { // do something here System.out.println("Hello SingletonDemo...."); }} |
現在是時候測試上面的Singleton類代碼。
1234567891011 | // Now it is time to use the above singleton class publicstaticvoidmain(Stringa[]) { // Create an object of the SingletonDemo class by calling getInstance() //static function of that class and use it's functionality. SingletonDemoobjSingleTone1=SingletonDemo.getInstance(); objSingleTone1.testFun(); //Note: If you will call like below, then it will give error message. // SingletonDemo objSingletonDemo = new SingletonDemo(); } |
關于單例設計模式的面試問題
我想分享我的實時面試經驗,有99%的機會,你會在你的電話采訪或面對面采訪中面對Singleton類的問題。所以準備好答案。在Singleton模式或Singleton類中找到一些常見問題。1.如何創建一個Singleton類。答:請檢查上面的代碼(SingletoneDemo類),以供參考。2.如何限制應用程序使用new運算符創建該類的對象。答案:通過將構造函數聲明為private并提供一個靜態方法來創建該類的新對象。請檢查上面的類(SingletoneDemo類)以供參考。3.如何在整個應用程序中只處理類的一個實例。答案:通過使用Singleton類。請檢查上面的類(SingletoneDemo類)以供參考。新聞熱點
疑難解答