单例模式:保证一个类仅有一个实例,并提供一个访问它的全局访问点。
为了不至于很快忘记,这里写三个最常用的方法如下:
Code
using System;
public class MyClass
{
private static MyClass instance;
private MyClass()
{
}
public static MyClass GetInstance()
{
if(instance==null)
{
instance=new MyClass();
}
return instance;
}
}
public class MyClass2
{
private static readonly object lockObject=new Object();
private static MyClass2 instance;
private MyClass2()
{
}
public static MyClass2 GetInstance()
{
if(instance==null)
{
lock(lockObject)
{
instance=new MyClass2();
}
}
return instance;
}
}
public class MyClass3
{
private static readonly MyClass3 instance=new MyClass3();
private MyClass3()
{
}
public static MyClass3 GetInstance()
{
return instance;
}
}
public class Test
{
public static void Main()
{
MyClass myClassOne=MyClass.GetInstance();
MyClass myClassTwo=MyClass.GetInstance();
ObjectCompare(myClassOne,myClassTwo);
MyClass2 myClass2One=MyClass2.GetInstance();
MyClass2 myClass2Two=MyClass2.GetInstance();
ObjectCompare(myClass2One,myClass2Two);
MyClass3 myClass3One=MyClass3.GetInstance();
MyClass3 myClass3Two=MyClass3.GetInstance();
ObjectCompare(myClass3One,myClass3Two);
Console.ReadLine();
}
public static void ObjectCompare(object o1,object o2)
{
if(o1==o2)
{
Console.WriteLine("OK");
}
else
{
Console.WriteLine("Not OK");
}
}
}
运行一下:
只有三个"ok"