01.单例模式基类模块
一、单例模式的构成
1、私有的静态成员变量
2、公共的静态成员属性或方法
3、私有构造函数
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class BaseManager : MonoBehaviour
{void Start(){}// Update is called once per framevoid Update(){}
}public class GameManager
{private static GameManager instance;public static GameManager GetInstance(){if (instance == null)instance = new GameManager();return instance;}
}
但是游戏中一般会有很多这样的单例模式,一个一个去写重复性的东西太多了。
二、使用泛型
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class BaseManager <T> where T:new()//泛型约束,要有无参构造函数
{private static T instance;public static T GetInstance(){if (instance == null)instance = new T();return instance;}
}public class GameManager:BaseManager<GameManager>//通过泛型传类型
{//减少重复代码
}
三、单例模式中的私有构造函数有什么作用?
私有构造函数的作用是阻止外部通过 new
关键字创建类的实例,确保类只能通过内部的单例实例访问,从而保证整个程序生命周期中仅存在一个类实例,符合单例模式 “唯一实例” 的核心特性。