C#/Unity3D 单例模板(单例属性模板)

C# 单例单例属性

不做过多解释,非面向大众
C#/Unity3D 单例模板(单例属性模板)_第1张图片

using System;
namespace EasyAVG
{
    public static class SingletonProperty<T> where T : class
    {

        private static readonly object locker = new object();
        private volatile static T instance = null;
        public static T Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (locker)
                    {
                        if (instance == null)
                        {
                            instance = Activator.CreateInstance<T>();
                        }
                    }
                }
                return instance;
            }
        }

        public static void Unload() => instance = null;
        public static void Reload() => instance = Activator.CreateInstance<T>();
    }

}

namespace EasyAVG
{
    public abstract class Singleton<T> where T : Singleton<T>
    {
        public static T Instance => SingletonProperty<T>.Instance;
        protected Singleton() { }


        public static void Unload() => SingletonProperty<T>.Unload();
        public static void Reload() => SingletonProperty<T>.Reload();
    }

}

Unity Mono单例 /单例属性模板

using UnityEngine;
namespace EasyAVG
{
    public static class MonoSingletonProperty<T> where T : MonoBehaviour
    {

        private static T instance = null;
        public static T Instance
        {
            get
            {
                if (instance == null) InitializeAfterSceneLoad();
                return instance;
            }
        }

        public static void InitializeAfterSceneLoad()
        {
            if (instance != null) return;
            GameObject container = new GameObject(typeof(T).Name);
            UnityEngine.Object.DontDestroyOnLoad(container);
            instance = container.AddComponent<T>();
        }

        public static void Unload()
        {
            UnityEngine.Object.Destroy(instance.gameObject);
            instance = null;
        }
        public static void Reload()
        {
            Unload();
            InitializeAfterSceneLoad();
        }
    }

}
using UnityEngine;


namespace EasyAVG
{
    public class MonoSingleton<T> : MonoBehaviour where T : MonoSingleton<T>
    {

        protected MonoSingleton() { }
        public static T Instance => MonoSingletonProperty<T>.Instance;


        public static void SingletonInitializeAfterSceneLoad() => MonoSingletonProperty<T>.InitializeAfterSceneLoad();

        public static void Unload() => MonoSingletonProperty<T>.Unload();
        public static void Reload() => MonoSingletonProperty<T>.Reload();
    }
}


你可能感兴趣的:(c#,开发语言)