單例設(shè)計(jì)模式(Singleton Class)
看看例子,并閱讀代碼行的注釋更清楚。這是java代碼,你可以使用C ++和.net編程使用相同的過(guò)程。| 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...."); }} |
現(xiàn)在是時(shí)候測(cè)試上面的Singleton類(lèi)代碼。
| 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(); } |
關(guān)于單例設(shè)計(jì)模式的面試問(wèn)題
我想分享我的實(shí)時(shí)面試經(jīng)驗(yàn),有99%的機(jī)會(huì),你會(huì)在你的電話采訪或面對(duì)面采訪中面對(duì)Singleton類(lèi)的問(wèn)題。所以準(zhǔn)備好答案。在Singleton模式或Singleton類(lèi)中找到一些常見(jiàn)問(wèn)題。1.如何創(chuàng)建一個(gè)Singleton類(lèi)。答:請(qǐng)檢查上面的代碼(SingletoneDemo類(lèi)),以供參考。2.如何限制應(yīng)用程序使用new運(yùn)算符創(chuàng)建該類(lèi)的對(duì)象。答案:通過(guò)將構(gòu)造函數(shù)聲明為private并提供一個(gè)靜態(tài)方法來(lái)創(chuàng)建該類(lèi)的新對(duì)象。請(qǐng)檢查上面的類(lèi)(SingletoneDemo類(lèi))以供參考。3.如何在整個(gè)應(yīng)用程序中只處理類(lèi)的一個(gè)實(shí)例。答案:通過(guò)使用Singleton類(lèi)。請(qǐng)檢查上面的類(lèi)(SingletoneDemo類(lèi))以供參考。新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注