代码:单件模式(Singleton Pattern)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DesignPatterns.Singletons
{
//一个类有且仅有一个实例,并且提供了一个全局的访问点
/// <summary>
/// 简单
/// </summary>
public sealed class Singleton01
{
static Singleton01 instance = null;
private Singleton01()
{
}
static Singleton01 Instance
{
get
{
if (instance == null)
{
instance = new Singleton01();
}
return instance;
}
}
}
/// <summary>
/// 线程安全,单锁:每次都锁,性能欠佳
/// </summary>
public sealed class Singleton02
{
static Singleton02 instance = null;
static readonly object olock = new object();
private Singleton02()
{
}
static Singleton02 Instance
{
get
{
lock (olock)
{
if (instance == null)
{
instance = new Singleton02();
}
return instance;
}
}
}
}
/// <summary>
/// 线程安全,双锁:为空时锁
/// </summary>
public sealed class Singleton03
{
static Singleton03 instance = null;
static readonly object olock = new object();
private Singleton03()
{
}
static Singleton03 Instance
{
get
{
if (instance == null)
{
lock (olock)
{
if (instance == null)//解决了线程并发问题,同时避免在每个 Instance 属性方法的调用中都出现独占锁定
{
instance = new Singleton03();
}
}
}
return instance;
}
}
}
/// <summary>
/// 静态初始化,实例化机制的控制权较少
/// </summary>
public sealed class Singleton04
{
static readonly Singleton04 instance = new Singleton04();
private Singleton04()
{
}
static Singleton04()
{
}
static Singleton04 Instance
{
get
{
return instance;
}
}
}
}


浙公网安备 33010602011771号