設計模式——單例模式

一:介紹

定義:確保一個類只有一個實例,並提供一個全局訪問點
單例模式是最簡單的設計模式之一,屬於建立型模式。計算機中的任務管理器,回收站是單例的典型應用場景
注意:
一、單例類只能有一個實例
二、單例類必須本身建立本身的惟一實例
三、單例類必須給全部其餘對象提供這一實例
設計模式


二:幾種單例模式的寫法

——餓漢式:在調用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

相關文章
相關標籤/搜索