没有使用lock的Singleton
public sealed class Singleton
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
{
Singleton()
{
}
public static Singleton Instance
{
get
{
return Nested.instance;
}
}
class Nested
{
static Nested()
{
}
internal static readonly Singleton instance = new Singleton();
}
}
泛型实现
1
public class Singleton<T> where T : new()
2
{
3
public static T Instance
4
{
5
get { return SingletonCreator.instance; }
6
}
7
8
class SingletonCreator
9
{
10
internal static readonly T instance = new T();
11
}
12
}
public class Singleton<T> where T : new()2
{3
public static T Instance4
{5
get { return SingletonCreator.instance; }6
}7

8
class SingletonCreator9
{10
internal static readonly T instance = new T();11
}12
}


浙公网安备 33010602011771号