很多人去实现单例的时候,通常会去写一个泛型的单例基类,
public class SingletonBase<T> where T : new()
{
static T instance;
public static T Instance
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}
然后让自己的单例类去继承他,以达到单例的效果。
我们都知道c#里面是不能多继承类的,所以当你这么写的时候,继承了单例基类之后就无法再去继承别的类了,比如MonoBehaviour。
因此这里向大家介绍另一种写法。
我们先实现一个单例泛型类。
public class Singleton<T> where T: new()
{
static T instance;
public static T Instance
{
get
{
if (instance == null)
instance = new T();
return instance;
}
}
}
然后再去写我们的一些单例类。
public class AudioManager
{
public void Print()
{
Debug.Log("音效管理器");
}
}
public class UIManager
{
public void OpenView()
{
Debug.Log("打开面板");
}
public void CloseView()
{
Debug.Log("关闭面板");
}
}```
然后我们这么去调用就可以实现单例的效果。
```csharp
public class Test : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Singleton<AudioManager>.Instance.Print();
Singleton<UIManager>.Instance.OpenView();
Singleton<UIManager>.Instance.CloseView();
}
// Update is called once per frame
void Update()
{
}
}
打印的结果是正确的,然后看到我们的UIManager和AudioManager是没有继承任何类的。
这里只是给大家介绍这种写法,泛型还可以这么写,而不是说让大家去这么写单例,单例的实现方法有很多种,大家自行选择。
希望对大家有帮助