首页 > 代码库 > 单例模式

单例模式

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
/*
* 单例模式
* 保证对象的唯一性
*/
namespace SingleDemo
{
class Program
{
static void Main(string[] args)
{
Single s1 = Single.GetInstance();
}
}
/// <summary>
/// 单例模式----饿汉模式 类加载对象就已经实例好了
/// </summary>
class Single
{
private static Single single = new Single();
/// <summary>
/// 私有化构造函数不让外部代码进行实例化
/// </summary>
private Single()
{

}
/// <summary>
/// 给外部开放一个方法获取实例
/// </summary>
/// <returns></returns>
public static Single GetInstance()
{
return single;
}
}


/// <summary>
/// 单例模式----懒汉模式(延迟加载)----调用GetInstance后才实例化
/// </summary>
class Single2
{
private static Single2 single2 = null;
/// <summary>
/// 私有化构造函数不让外部代码进行实例化
/// </summary>
private Single2()
{ }
/// <summary>
/// 给外部开放一个方法获取实例
/// </summary>
/// <returns></returns>
public static Single2 GetInstance()
{
if (single2 == null)
single2 = new Single2();
return single2;
}
}


}