不继承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.多线程问题:当多个线程同时访问管理器时,可能会出现共享资源的安全访问问题

相关推荐
肯多洛夫斯基1 小时前
安卓工控屏静默连WiFi全攻略
android
极梦网络无忧1 小时前
Android无障碍服务实现抖音直播间界面监控(场控助手核心原理)
android
call me by ur name2 小时前
ERNIE 5.0 Technical Report论文解读
android·开发语言·人工智能·机器学习·ai·kotlin
kerli2 小时前
Compose 组件:Box 核心参数及其 Bias 算法
android·前端
BLUcoding3 小时前
Android 常用控件及核心属性
android
遥不可及zzz3 小时前
[特殊字符] Android AAB 一键安装工具配置指南
android·macos
私人珍藏库3 小时前
【Android】一键硬核锁手机
android·智能手机·app·工具·软件
TTTao23334 小时前
自用Android项目框架备份
android
沃尔威武4 小时前
性能调优实战:从火焰图定位到SQL优化的全流程
android·数据库·sql
Fᴏʀ ʏ꯭ᴏ꯭ᴜ꯭.4 小时前
基于MySQL一主一从环境添加多个新从库
android·mysql·adb