单例模式:
步骤:
1.定义静态私有对象
2.构造函数私有化
3.定义一个静态的,返回值为该类型的方法,一般以Getinstance/getInit为方法名称
单例模式有懒汉和饿汉,最好使用饿汉
1.饿汉式---先实例化
public class Singleton
{
private static Singleton _singleton = new Singleton();//1
private Singleton() //2
{
}
public static Singleton GetInstance() //3
{ return _singleton;
} }
2.懒汉式---后实例化
using System;
namespace 单例懒汉
{
public class Singleton
{
private static Singleton _singleton; //1
private Singleton() // 2
{ }
public static Singleton GetInstance() 3
{
if (_singleton == null)
{
_singleton = new Singleton();
}
return _singleton;
}
}
}