[英]Generic Abstract Singleton with Custom Constructor in C#
我想编写一个带有外部构造函数的通用单例。 换句话说,可以修改构造函数。 我的脑海中有2种设计,但我不知道它们是否实用。
第一个是强制派生类的构造函数是非公共的,但我不知道是否有办法吗?
第二个是使用委托并在构造函数内部调用它?
不一定要成为构造函数。 我选择自定义构造函数的原因是进行了一些自定义初始化。
任何建议,将不胜感激 :)
听起来不太好。 我想知道通过IoC进行配置是否会变得更加简单和易于支持。 大多数IoC容器将支持singeton样式的对象重用以及高度可配置的初始化。 没有副作用,使您的对象很难看。
Singleton很不错,但是过度使用了。 当然,我和下一个极客一样感到内......
这是执行此操作的一种方法,如果可以的话,我完全可以帮助您。
public abstract class MySingletonBase<T>
where T : class
{
protected MySingletonBase()
{
}
// All other functions that will be inherited.
}
public class MySingleton<T> : MySingletonBase<T>
where T : class
{
private static MySingleton<T> instance;
protected MySingleton()
{
}
public static MySingleton<T> GetInstance()
{
if (instance == null)
{
instance = new MySingleton<T>();
}
return instance;
}
}
这是我的观点,使用.NET 4
public class Singleton<T> where T : class, new()
{
Singleton (){}
private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());
public static T Instance { get { return instance.Value; } }
}
您可以尝试使用工厂模式创建单例工厂,该工厂将产生具体的单例。
好的,这是我的解决方案。 我使用反射来检查公共构造函数。 如果我缺少什么,请发表评论。
public abstract class Singleton<T> where T: class
{
private static volatile T _instance;
private static object _lock = new object();
protected Singleton()
{
ConstructorInfo[] constructorPublic = typeof(T).GetConstructors(BindingFlags.Public | BindingFlags.Instance);
if (constructorPublic.Length > 0)
{
throw new Exception(String.Format("{0} has one or more public constructors so the property cannot be enforced.",
typeof(T).FullName));
}
}
public static T Instance
{
get
{
if (_instance == null)
{
lock (_lock)
{
if (_instance == null)
{
ConstructorInfo constructorNonPublic = null;
try
{
constructorNonPublic = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null,
new Type[0], null);
}
catch (Exception e)
{
throw e;
}
if (constructorNonPublic == null || constructorNonPublic.IsAssembly)
{
throw new Exception(String.Format("A private or protected constructor is missing for {0}",
typeof (T).Name));
}
_instance = constructorNonPublic.Invoke(null) as T;
}
}
}
return _instance;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.