设计模式-单件模式(Singleton pattern)
模式描述:确保一个类只有一个实例,并提供访问这个实例的全局点.
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Singelton
{
class Program
{
static void Main(string[] args)
{
Singleton S1= Singleton.GetInstance();
Singleton S2=Singleton.Instance;
Console.WriteLine(System.Object.ReferenceEquals(S1, S2));
Console.ReadLine();
}
}
class Singleton
{
//惰性化实例一个对象,不管你是否调用这个实例,它都会被创建。
private static readonly Singleton instance=new Singleton();
private Singleton()
{
}
/// <summary>
/// 通过属性返回唯一实例
/// </summary>
public static Singleton Instance
{
get { return instance; }
}
/// <summary>
/// 通过方法返回唯一实例
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
return instance;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Singelton
{
class Program
{
static void Main(string[] args)
{
Singleton S1= Singleton.GetInstance();
Singleton S2=Singleton.Instance;
Console.WriteLine(System.Object.ReferenceEquals(S1, S2));
Console.ReadLine();
}
}
class Singleton
{
//惰性化实例一个对象,不管你是否调用这个实例,它都会被创建。
private static readonly Singleton instance=new Singleton();
private Singleton()
{
}
/// <summary>
/// 通过属性返回唯一实例
/// </summary>
public static Singleton Instance
{
get { return instance; }
}
/// <summary>
/// 通过方法返回唯一实例
/// </summary>
/// <returns></returns>
public static Singleton GetInstance()
{
return instance;
}
}
}
Demo中返回的S1和S2其实都是同一个引用。