public class Singleton<T> : IDisposable where T : class
{
protected Singleton() { }
protected static object[] mutex = new object[] { };
protected static T _default;
public static T Default
{
get
{
if (_default == null)
{
lock (mutex)
{
if (_default == null)
{
Type type = typeof(T);
var ctor = type.GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, Type.DefaultBinder, Type.EmptyTypes, null);
if (ctor == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");
object instance = ctor.Invoke(null);
if (instance == null) throw new Exception($" type `{type.FullName}` miss a none paramters constructor .");
_default = (instance as T);
}
}
}
return _default;
}
}
public void Dispose()
{
_default = null;
}
}
这是一种通过反射实例化单列对象,虽然反射会牺牲一些性能,但是单例至始至终也只会实例化一次,所以这点消耗是可以接受的。
// 使用继承方式,实现单例
public class HttpClientFactory : Singleton<HttpClientFactory>
{
public enum HttpClientKind
{
Restful = 0,
File = 1
}
private readonly ConcurrentBag<IHttpClient> httpClents;
// 可以私有化构造函数,外部无法构造此对象,实现真正意义的单例。
private HttpClientFactory()
{
httpClents = new ConcurrentBag<IHttpClient>();
}
...
}
优点:复用性好,可以私有化构造函数
缺点:反射消耗性能(可以忽略不计)
|