public class SingLeton
{
private static SingLeton instance;
private SingLeton()
{
instance = new SingLeton();
}
public static SingLeton Instace
{
get{return instance;}
}
}
2.懒汉模式:第一次调用时才创建该单例对象
优点:在需要时创建,利用率高;提高启动速度
缺点:多线程不安全,可能会创建多个实例
应用场景:单例对象功能复杂,内存占用大,需要快速启动
public class LazySingleton
{
private static LSingleton _instance;
public static Singleton Instace
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
}
}
public sealed class Singleton
{
private Singleton() { }
private static Singleton _instance;
public static Singleton GetInstance()
{
if (_instance == null)
{
_instance = new Singleton();
}
return _instance;
}
public void someBusinessLogic()
{
// ...
}
}