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

相关推荐
alexhilton4 小时前
突破速度障碍:非阻塞启动画面如何将Android 应用启动时间缩短90%
android·kotlin·android jetpack
kobe_OKOK_5 小时前
Django `models.Field` 所有常见配置参数的完整清单与说明表
android
前行的小黑炭6 小时前
Android Compose :初步了解一下生命周期,对比原生android
android·kotlin·app
湖南人爱科技有限公司7 小时前
RaPhp和Python某音最新bd-ticket-guard-client-data加密算法解析(视频评论)
android·python·php·音视频·爬山算法·raphp
守城小轩11 小时前
Chromium 138 编译指南 - Android 篇:从Linux版切换到Android版(六)
android·chrome·指纹浏览器·浏览器开发·超级浏览器
守城小轩11 小时前
Chromium 138 编译指南 - Android 篇:环境搭建与准备(一)
android·chrome·指纹浏览器·浏览器开发
消失的旧时光-194312 小时前
Kotlin when 用法完整分享
android·开发语言·kotlin
顾林海14 小时前
Android编译插桩黑科技:ReDex带你给App"瘦个身,提个速"
android·面试·性能优化
maki07714 小时前
VR大空间资料 04 —— VRAF使用体验和源码分析
android·vr·虚幻·源码分析
消失的旧时光-194317 小时前
Kotlin 判空写法对比与最佳实践
android·java·kotlin