目录
一.引言
在C#中需要批量创生单例类时,一个个的写类实在时太累了.于是为了省力,我们要写一个父类,当继承了这个父类就可以成为单例类.
二.代码样例
using System;
using System.Collections;
using System.Collections.Generic;
public class Singleton<T> where T : Singleton<T>,new()
{ //static前缀使得可以通过类名.属性名来访问该属性
private static T instance = null;
public static T Instance
{ //只有get方法没有set方法,意味Instance对其他类为只读
get
{ //如果instance为空,则重新初始化instance为指向T类实例的指针
if (instance == null)
{
instance = new T();
}
//否则返回唯一的instance属性
return instance;
}
}
}
1.where说明:
public class Singleton<T> where T : Singleton<T>,new()
where T : class意味着对T的类型约束,即T必须为class类或者class类的子类
where T: new()意味着该类型必须具有无参数构造函数。有了这个约束将允许这样初始化T类型的实例
T instance = new T();
否则不能这样初始化一个实例
用逗号结合两者得到
where T : class,new()
//此例中为
where T : Singleton<T>,new()
三.Unity中的运用
如我们要初始化一个中央银行,中央银行只能存在一个,方便统一管理所有人的数据
则首先写一个 Singleton的父类脚本
注意:1.这里没有在where后添加new(),因为我们使用instance=(T)this来初始化.
2.含有static的属性在类被创建时就被储存在静态储存区中,而不是在类被实体化时被创建,并且全局只创建一次,也就是只有一份.
3.只有当Singleton<T>的子类第一个对象被初始化时会改变 子类名.instance 的值为指向该对象指针,之后的对象初始化时会自动销毁.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Singleton<T> :MonoBehaviour where T : Singleton<T>
{
private static T instance;
public static T Instance
{
//只能被访问,不能被改写
get { return instance; }
}
//protected意味只能被该类或者子类访问
//virtual意味着子类可以改写该方法
//Awake在脚本对象创建后立刻调用
protected virtual void Awake()
{
//如果有本类instance存在(代表已经存在一个对象),则销毁该对象
//否则instance指向该对象
if (instance != null)
Destroy(instance);
else
instance = (T)this;
}
}
1.编写单例子类CentralBank脚本
public class CentralBank:Singleton<CentralBank>
{
}
四.关于泛型如Singleton<T>的补充说明:
希望能有帮助