[英]Is there a way to populate a base class singleton instance with a derived class?
我有一個基礎播放器類,其中包含一個Singleton聲明。 我想用derivedClass填充baseClass.Instance var,如果可能的話。
我當前的方法是,當derivedClass“喚醒”時,它會嘗試設置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)
{
...
}
}
}
使用工廠類返回單例實例。 例如
public static class PlayerFactory
{
private static BasePlayer _instance;
public static BasePlayer Instance
{
get { return _instance; }
protected set { _instance = value; }
}
}
它應該接受來自BasePlayer的任何對象作為單個實例。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.