创建型模式:主要聚焦于对象是如何创建的。
单例模式,在任何情况下,只允许有一个对象的实例。
1. 单线程下的单例模式:
public class SingletonTest
{
private static SingletonTest instance;
private SingletonTest() { }
public static SingletonTest Instance
{
get
{
if (instance == null)
{
instance = new SingletonTest();
}
return instance;
}
}
}
2. 多线程情况下的单例模式:
public class SingleTestThread
{
private static volatile SingleTestThread instance;
private static object lockHelper = new object();
private SingleTestThread() { }
public static SingleTestThread Instance
{
get
{
if (instance == null)
{
lock (lockHelper)
{
if (instance == null)
{
instance = new SingleTestThread();
}
}
}
return instance;
}
}
}
3.任何情况下都可以用,但是没办法传参:
public class SingleSimple
{
private SingleSimple() { }
public static readonly SingleSimple Instance = new SingleSimple();
}