【问题标题】:Is there a way to populate a base class singleton instance with a derived class?有没有办法用派生类填充基类单例实例?
【发布时间】:2019-08-31 01:11:32
【问题描述】:

我有一个基播放器类,其中包含一个单例声明。如果可能的话,我想用派生类填充 baseClass.Instance var。

我目前的做法是,当派生类“唤醒”时,它会尝试设置 Instance = this;我也试过调用 base.Init(),然后设置 Instance = this;在 base.Init() 方法中。这会设置 Instance != null,但 Instance != derivedClass 也是如此。

// 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)
        {
            ...
        }
    }
}

【问题讨论】:

  • 不应派生单例类。
  • 在这种情况下,我应该将 Singleton 移动到派生类吗?例如FPSPlayer.Instance?

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


【解决方案1】:

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

public static class PlayerFactory
{
   private static BasePlayer _instance;

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

它应该接受从 BasePlayer 继承的任何对象作为单个实例。

【讨论】:

  • 啊,这是缺少的部分。谢谢!
猜你喜欢
  • 2014-03-22
  • 2021-11-16
  • 1970-01-01
  • 2016-07-06
  • 2014-04-27
  • 1970-01-01
  • 1970-01-01
  • 2013-02-12
  • 2019-07-25
相关资源
最近更新 更多