单例模式基类模块
单例模式 -- 一种创建型模式,一个类负责创建自己的实例,且同时确保只有单个实例可以被创建
-- 对外提供一个访问该实例的方式
Unity中单例模式的坑 -- 不能通过构造函数实现
https://blog.csdn.net/younglady2015/article/details/82752851
Unity官方的建议:Avoid using the constructor. Never initialize any values in the constructor. Instead use Awake or Start for this purpose.
没必要在继承自MonoBehaviour类的构造函数中写任何代码。
解释:无法预计何时会调用构造函数
单例模式的多种实现方法:https://www.jianshu.com/p/3ffabd9ecd29
官方推荐实现方法:
public class Singleton : MonoBehaviour { public static Singleton instance; private Singleton(); void Awake() { instance = this; } public static GetInstance() { return instance; } }
教程中实现方法:
惰性加载 Lazy-Loading;不是线程安全的,没有synchronized加锁(解释:小游戏开发中基本上不会用到多线程,若有多线程则需加双锁)
public class Singleton { private static Singleton instance; public static Singleton GetInstance() { if(instance == null) { instance = new Singleton(); } return instance; } }
单例模式基类 -- 每一个类的单例模式实现代码都是相似的,使用单例模式基类可以减少重复代码的书写
public class SingletonBase<T> where : new () { // where关键字给泛型T做限定:有一个无参构造函数new () private static T instance; public static T GetInstance() { if(instance == null) { instance = new T(); } return instance; } } public class Singleton : SingletonBase<Singleton> { }