单例设计模式(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类)以供参考。新闻热点
疑难解答