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

相关推荐
hunterandroid8 分钟前
Retrofit 网络请求的异常处理与重试策略实战
android
sejinan31 分钟前
极致轻量与秒级起播:NativeWasmTv 开源硬核技术解析与升级版体验
android·开源·webview·tv
小羊没烦恼!41 分钟前
Ajax与JSON的一些总结
android·java·前端·数据库·mysql·算法·okhttp
mmsx1 小时前
Android 静默失败实录:五个没有日志的线上事故
android·kotlin
hai_android2 小时前
从零实现一个支持跨进程(IPC)的自定义 Toast
android·kotlin·android jetpack
龙腾-虎跃2 小时前
基于 SIP 协议的自研电话终端:FreeSWITCH 语音与视频通信实战
android·音视频·freeswitch·sip协议终端·wertc
imDwAaY2 小时前
操作系统如何管理程序运行?从线程、进程到内存隔离与用户态切换:CS162 Note2
android·java·redis
andyweike3 小时前
Android文件系统
android
studyForMokey3 小时前
【Android 面试】Paging3
android·面试·职场和发展
企业数字化笔记3 小时前
租户停用后数据和任务怎么处理?冻结、恢复与保留策略的实现
android·java·spring boot