设计模式-单例模式

一、单例模式
它写起来简单,使用起来也是爽的飞起,可以全局访问,想点哪里点哪里。
保证一个类仅有一个实例,并且有生命周期
提供一个全局访问点,在任何地方都可以获取
单一例子实例化
以上基本上就是它的作用了,作者是 Unity3D游戏开发的童鞋,使用到的框架中全场只有一个大单例,不会说出现空指针的情况,但是如果使用多单例的话很容易出现一个获取的先后问题而报错。 但是这里博主还是将单例模板进行列举出来。。

Mono单例

//==========================
// - FileName:      MonoSingleton.cs         
// - Created:       true.	
// - CreateTime:    2020/02/28 22:24:15	
// - Email:         1670328571@qq.com		
// - Region:        China WUHAN	
// - Description:   
//==========================
using UnityEngine;

public abstract class MonoSingleton<T> : MonoBehaviour where T : MonoBehaviour
{
    private static T _instance = null;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<T>();
                if (_instance == null)
                {
                    Debug.LogError("Scene Dont NullObject" + typeof(T).Name);
                }
            }
            return _instance;
        }
    }

    private void Awake()
    {
        //if (_instance == null)
        //{
        //    DontDestroyOnLoad(gameObject);
        //}
        //else
        //{
        //    Destroy(gameObject);
        //}

        _instance = this as T;

    }
}


普通单例:

//==========================
// - FileName:      SingletonNormal.cs         
// - Created:       true.	
// - CreateTime:    2020/10/19 23:23:11	
// - Email:         1670328571@qq.com		
// - Region:        China WUHAN	
// - Description:   普通单例类
//==========================
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class NormalSingleton<T>  where  T : class,new ()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance  == null)
            {
                T t = new T();
                if (t is MonoBehaviour)
                {
                    Debug.LogError("Normal Singleton Not Instance MonoSingleton");
                }
                _instance = t;
            }
            return _instance;
        }
    }
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值