不继承Mono的单例模式基类

1. 为什么要写写单例模式基类

用面向对象的思想避免代码冗余(多余、重复)

2. 实现不继承MonoBehaviour的单例模式基类

单例模式的基类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 单例模式基类,主要目的是避免代码的冗余,方便实现单例模式的类
/// </summary>
/// <typeparam name="T"></typeparam>
//where约束T必须是class,还有有一个公共的无参构造函数
public class BaseManager<T> where T : class,new()
{
    public static T instance;

    // 属性的方式
    public static T Instance
    {
        get
        {
            if(instance == null)
            {
                instance = new T();
            }
            return instance;
        }
    }

    // 方法的方式
    public static T GetInstance()
    {
        if(instance == null)
        {
            instance = new T();
        }
        return instance;
    }
}

当其他类需要实现单例时候,直接继承基类

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestMgr : BaseManager<TestMgr>
{

    public void TestLog()
    {
        Debug.Log("Test");

    }
    
}

好处就是可以避免代码冗余,不用重复定义单例,需要单例直接继承就行

csharp 复制代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TestMgr2 : BaseManager<TestMgr2>
{
    public void TestLog()
    {
        Debug.Log("test2");
    }
    
}

测试

csharp 复制代码
public class Main : MonoBehaviour
{
    // Start is called before the first frame update
    void Start()
    {
        TestMgr.Instance.TestLog();
        TestMgr2.Instance.TestLog();
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

3. 潜在的安全问题

1.构造函数问题:构造函数可在外部调用 可能会破坏唯一性

比如csharp TestMgr t = new TestMgr(); 不能new一个单例模式的对象,可以通过反射解决

2.多线程问题:当多个线程同时访问管理器时,可能会出现共享资源的安全访问问题

相关推荐
疯华整猫6 分钟前
别再抄 Flutter 了:2026 年 Android / iOS / 小程序跨端架构选型的四本成本账
android·前端·ios
传奇开心果编程25 分钟前
【Flutter踩坑排雷】第30课:异常未捕获坑|未捕获异常直接闪退,全局兜底故障处理
android·flutter·ios·移动开发·dart·ui框架·声明式ui
恋猫de小郭2 小时前
Flutter Native Interop 稳定了,Platform Channel 要退场了
android·前端·flutter
好的佩奇12 小时前
Dart 之可迭代对象与生成器
android·flutter·dart
_祝你今天愉快13 小时前
Paint Cavans高级绘制:[三] Canvas高阶使用技巧-变换,状态保存,离屏缓冲,粒子特效
android
小乖写代码13 小时前
提交注册验证 · WhatsApp /v2/register
android·网络·账号注册
二流小码农17 小时前
鸿蒙开发:router组件升级,彻底告别手动配置
android·ios·harmonyos
Digitally18 小时前
如何在安卓设备上使用 4 种简单方法将应用移动到 SD 卡
android
booboosui20 小时前
录一遍就会:8 种步骤、6 类失败,卡住时只修那一步
android
阿杰m20 小时前
Android源码第十五章:Camera2 与 CameraService——一帧图像怎样回到应用
android