题目:设计一个类,我们只能生成该类的一个实例。
转载请注明出处:http://blog.csdn.net/lvsaixia/article/details/39583193
只能生成一个实例的类是实现Singleton(单例)模式的类型。由于设计模式在面向对象程序设计中起着举足轻重的作用,面试中经常会出现这样的面试题。
不好得解决方法一:只适用于单线程环境
public sealed class Singleton
{
private singleton()
{
}
private static Singleton instance = null;
public static Singleton Instance{
get
{
if (instance == null)
instance = new Singleton();
return instance;
}
}
}
不好的解法二:虽然在多线程环境中能工作但是工作效率不高
public sealed class Singleton
{
private singleton()
{
}
private static readonly object syncObj = new object();
private static Singleton instance = null;
public static Singleton Instance{
get
{
lock(syncObj){
if (instance == null)
instance = new Singleton();
}
return instance;
}
}
}
public sealed class Singleton
{
private singleton()
{
}
private static readonly object syncObj = new object();
private static Singleton instance = null;
public static Singleton Instance{
get
{
if (instance == null)
lock(syncObj)
{
instance = new Singleton();
}
}
return instance;
}
}
推荐的解法一:利用静态构造函数
public sealed class Singleton
{
private singleton()
{
}
private static Singleton instance = new Singleton();
public static Singleton Instance{
get
{
return instance;
}
}
}
推荐的解法二:实现按需创建实例
public sealed class Singleton
{
private singleton()
{
}
public static Singleton Instance{
get
{
return instance;
}
}
class Nested{
static Nested(){}
insternal static readonly Singleton instance = new Singleton();
}
}
请阅读这篇博客。博主详细讲解了23种设计模式。
转载请注明出处:http://blog.csdn.net/lvsaixia/article/details/39583193