意图:出于某种目的(如性能考虑、逻辑性要求)要求一个类的实例只能有N个
应用:抽象工厂模式中的工厂类、对象池
应用:抽象工厂模式中的工厂类、对象池
namespace DesignPattern.Singleton
{
// 单线程
public class SingleThread
{
private static SingleThread instance;
private SingleThread()
{
}
public static SingleThread Instance
{
get
{
if (instance == null)
{
instance = new SingleThread();
}
return instance;
}
}
// 使用.NET静态对象实例化机制以如下一行代码实现,此方式简单,但是不能在构造函数中进行初始化处理,当然可以通过调用自定义方法初始化。
// public static readonly SingleThread Instance = new SingleThread();
}
// 多线程
public class MultiThread
{
private static volatile MultiThread instance;
private static object obj = new object();
private MultiThread()
{
}
public static MultiThread Instance
{
get
{
if (instance == null)
{
lock (obj)
{
if (instance == null)
{
instance = new MultiThread();
}
}
}
return instance;
}
}
}
}
{
// 单线程
public class SingleThread
{
private static SingleThread instance;
private SingleThread()
{
}
public static SingleThread Instance
{
get
{
if (instance == null)
{
instance = new SingleThread();
}
return instance;
}
}
// 使用.NET静态对象实例化机制以如下一行代码实现,此方式简单,但是不能在构造函数中进行初始化处理,当然可以通过调用自定义方法初始化。
// public static readonly SingleThread Instance = new SingleThread();
}
// 多线程
public class MultiThread
{
private static volatile MultiThread instance;
private static object obj = new object();
private MultiThread()
{
}
public static MultiThread Instance
{
get
{
if (instance == null)
{
lock (obj)
{
if (instance == null)
{
instance = new MultiThread();
}
}
}
return instance;
}
}
}
}
欢迎光临我的淘宝http://shop35795100.taobao.com,专营游戏点卡、电话卡及各类充值卡。