网上大部分的单例实现都要求在类里添加一个”GetInstance()”并且声明私有的构造函数,额外多了几行没啥用且重复的代码,一不小心还会忘记把构造函数搞成私有的,非常不爽,所以就搞了个这东西

不多说,上代码,使用的时候只需要public class ClassName : Singleton<ClassName>即可,获取实例直接ClassName.Instance,无需额外的更改

using System;
using System.Collections.Generic;

namespace InstanceHelper.Singleton {
public class Singleton<T> {
private static Dictionary<Type, Object> TypeObjectMap = new Dictionary<Type, Object>();
private static List<Type> TypeLoadList = new List<Type>();

static public T Instance { get => GetInstance(typeof(T)); }

public Singleton() {
lock (TypeLoadList) {
if (!TypeLoadList.Contains(this.GetType())) {
throw new NewSingletonClassException(String.Format("Class {0} is Singleton, Use \"{1}.Instance;\" but \"new {1}();\"", this.GetType().FullName, this.GetType().Name));
}
}
}

private static void LockUnregisterTypeLoadStatus(Type _Type) {
lock (TypeLoadList) {
if (TypeLoadList.Contains(_Type)) {
TypeLoadList.Remove(_Type);
}
}
}

private static void LockRegisterTypeLoadStatus(Type _Type) {
lock (TypeLoadList) {
if (!TypeLoadList.Contains(_Type)) {
TypeLoadList.Add(_Type);
}
}
}

protected static T GetInstance(Type _Type) {
if (!TypeObjectMap.ContainsKey(_Type)) {
lock (TypeObjectMap) {
if (!TypeObjectMap.ContainsKey(_Type)) {
LockRegisterTypeLoadStatus(_Type);
var Instance = Activator.CreateInstance(_Type);
LockUnregisterTypeLoadStatus(_Type);
TypeObjectMap.Add(_Type, Instance);
}
}
}
return (T)TypeObjectMap[_Type];
}
}
}