0
点赞
收藏
分享

微信扫一扫

Singleton设计模式 - 创造性设计模式


顾名思义,Singleton意味着“单实例”。因为它是一个创造性的设计模式,所以这种设计模式提供了解决方案,在整个应用程序的生命周期只创建一个类的一个对象(实例)。这意味着您可以通过提供一个静态成员来限制给定类的对象的创建函数仅为该类创建一个对象。一旦对象第一次创建,那么如果你将尝试为同一个类创建另一个对象,那么它将返回现有对象的引用(活对象的引用)给你。这样,它可以限制到特定类的一个对象。



要仅限制类的一个对象创建,您必须按照以下步骤。



创建Singleton类的步骤

创建类(可以使用C ++ / Java / .Net编程语言创建类)


使默认构造函数为private,以便没有人可以使用operator new / calloc / malloc operator等创建任何对象。


使用相同类型的私有变量来跟踪对象是否已经被创建,只需检查变量的空值,如果它不为null,那么只返回该对象的现有引用。如果对象没有被创建,那么只使用普通的new操作符首次创建类的一个对象,然后返回创建的对象的引用。


定义一个静态成员函数,可以被其他类访问以调用创建此类的对象。



单例设计模式(Singleton Class)

看看例子,并阅读代码行的注释更清楚。这是java代码,你可以使用C ++和.net编程使用相同的过程。












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类代码。


// Now it is time to use the above singleton class


public static void main ( String a [ ] )


{


// Create an object of the SingletonDemo class by calling getInstance() //static function of that class and use it's functionality.





SingletonDemo objSingleTone1 = SingletonDemo . getInstance ( ) ;


objSingleTone1 . testFun ( ) ;





//Note: If you will call like below, then it will give error message.


// SingletonDemo objSingletonDemo = new SingletonDemo();


}








  • 使用Singleton设计模式

此设计模式通常用于以下应用程序类型。它保存网络特定数据,如果一个服务器将在特定时间停机,那么它也可以同时管理您的请求与其他服务器。


如果要将当前数据或对象的更新共享给所有其他模块,则此单例设计模式是最好的方法。


您还可以使用下面提到的单例模式开发不同类型的应用程序。


银行应用程序


财务应用


旅游应用


系统服务类



关于单例设计模式的面试问题

我想分享我的实时面试经验,有99%的机会,你会在你的电话采访或面对面采访中面对Singleton类的问题。所以准备好答案。在Singleton模式或Singleton类中找到一些常见问题。



1.如何创建一个Singleton类。


答:请检查上面的代码(SingletoneDemo类),以供参考。



2.如何限制应用程序使用new运算符创建该类的对象。


答案:通过将构造函数声明为private并提供一个静态方法来创建该类的新对象。请检查上面的类(SingletoneDemo类)以供参考。



3.如何在整个应用程序中只处理类的一个实例。


答案:通过使用Singleton类。请检查上面的类(SingletoneDemo类)以供参考。

举报

相关推荐

0 条评论