设计模式——单例模式

一:介绍

定义:确保一个类只有一个实例,并提供一个全局访问点
单例模式是最简单的设计模式之一,属于建立型模式。计算机中的任务管理器,回收站是单例的典型应用场景
注意:
一、单例类只能有一个实例
二、单例类必须本身建立本身的惟一实例
三、单例类必须给全部其余对象提供这一实例
设计模式


二:几种单例模式的写法

——饿汉式:在调用Instance对象以前就实例化对象ide

using System;
using UnityEngine;

public class Singleton : MonoBehaviour
{
    //继承MonoBehaviour
    private static Singleton _instance;
    public static Singleton Instance
    {
        get { return _instance; }
    }

    private void Awake()
    {
        _instance = this;
    }

//    //不继承MonoBehaviour
//    private static Singleton _instance = new Singleton();
//    public static Singleton Instance
//    {
//        get { return _instance; }
//    }
}


——懒汉式:在调用Instance对象以后才实例化对象this

using System;
using UnityEngine;

public class Singleton : MonoBehaviour
{
    //继承MonoBehaviour
    private static Singleton _instance;
    public static Singleton Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = FindObjectOfType<Singleton>();
            }
            return _instance;
        }
    }

//    //不继承MonoBehaviour
//    private static Singleton _instance;
//    public static Singleton Instance
//    {
//        get
//        {
//            if (_instance == null)
//            {
//                _instance = new Singleton();
//            }
//            return _instance;
//        }
//    }
}

三:单例模版

——单例类模板(继承MonoBehaviour)spa

using UnityEngine;

/// <summary>
/// 继承Mono的单例模版
/// </summary>
public abstract class MonoSingleton<T> : MonoBehaviour
    where T : MonoBehaviour
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                GameObject go = new GameObject(typeof(T).ToString());
                DontDestroyOnLoad(go);
                _instance = go.AddComponent<T>();
            }
            return _instance;
        }
    }
}


 


——单例类模板(不继承MonoBehaviour)设计

/// <summary>
/// 不继承Mono的单例模版
/// </summary>
public abstract class Singleton<T>
    where T : new()
{
    private static T _instance;
    public static T Instance
    {
        get
        {
            if (_instance == null)
            {
                _instance = new T();
                (_instance as Singleton<T>).Init();
            }
            return _instance;
        }
    }

    /// <summary>
    /// 子类初始化的一些操做
    /// </summary>
    protected virtual void Init()
    {

    }
}

将模版定义为抽象类是为了让单例类不能被实例化,须要被继承后才能实例化code

相关文章
相关标签/搜索