using System;

namespace ET
{
    // 定义一个接口 ISingleton,用于实现单例模式
    public interface ISingleton: IDisposable
    {
        // 注册单例对象
        void Register();
        // 销毁单例对象
        void Destroy();
        // 判断单例对象是否已经被销毁
        bool IsDisposed();
    }

    // 定义一个抽象类 Singleton<T>,继承自 ISingleton 接口,用于创建泛型的单例对象
    public abstract class Singleton<T>: ISingleton where T: Singleton<T>, new()
    {
        private bool isDisposed;
        [StaticField]
        private static T instance;

        public static T Instance
        {
            get
            {
                return instance;
            }
        }

        void ISingleton.Register()
        {
            if (instance != null)
            {
                throw new Exception($"singleton register twice! {typeof (T).Name}");
            }
            instance = (T)this;
        }

        void ISingleton.Destroy()
        {
            if (this.isDisposed)
            {
                return;
            }
            this.isDisposed = true;
            
            instance.Dispose();
            instance = null;
        }

        bool ISingleton.IsDisposed()
        {
            return this.isDisposed;
        }

        public virtual void Dispose()
        {
        }
    }
}