有没有一种方法可以用派生类填充基类单例实例?

时间:2019-04-09 17:08:52

标签: c# singleton superclass derived-class base-class

我有一个基本的玩家类,其中包含一个Singleton声明。如果可能的话,我想用derivedClass填充baseClass.Instance var。

我当前的方法是,当派生类“醒来”时,它尝试设置Instance = this;我也尝试调用base.Init(),然后设置Instance = this;。在base.Init()方法中。这会将Instance!=设置为null,但将Instance!=衍生类设置为null。

// Current approach
public abstract class BasePlayer : Entity, IPlayerBase
{
    // Singleton instance, to be populated by the derived class
    private static BasePlayer _i = null;
    private static object _lock = new object();
    private static bool _disposing = false; // Check if we're in the process of disposing this singleton

    public static BasePlayer Instance
    {
        get
        {
            if (_disposing)
                return null;
            else
                return _i;
        }

        protected set
        {
            lock (_lock)
            {
                if(_i == null && !_disposing)
                    _i = value;
            }
        }
    }

    protected void Init()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != null)
        {
            Active = false;
            Destroy(this.gameObject);
        }

        if (Instance == this)
        {
            Debug.Log("Successfully set BaseClass");
            ...
        }
    }
}
// Current approach
public class FPSPlayer : BasePlayer
{
    void OnEnable()
    {
        base.Init();
    }
}
// Also tried
public class FPSPlayer : BasePlayer
{
    void OnEnable()
    {
        if (Instance == null)
        {
            Instance = this;
        }
        else if (Instance != null)
        {
            Active = false;
            Destroy(this.gameObject);
        }

        if (Instance == this)
        {
            ...
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用工厂类返回您的单例实例。例如

public static class PlayerFactory
{
   private static BasePlayer _instance;

   public static BasePlayer Instance 
   {
      get { return _instance; }
      protected set { _instance = value; }
   } 
}

应将BasePlayer派生的任何对象作为单个实例。

相关问题