一、單例模式的構成
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
?關鍵字創建類的實例,確保類只能通過內部的單例實例訪問,從而保證整個程序生命周期中僅存在一個類實例,符合單例模式 “唯一實例” 的核心特性。