带接口的状态设计模式



我正在读一本关于 Unity 设计模式的书,我了解了"状态模式"。对我来说,令人好奇的是,这是我第一次看到这种模式与接口一起使用。他使用接口创建所有状态。

public class Ship : MonoBehaviour
{
private IShipState m_CurrentState;
private void Awake()
{
IShipState m_CurrentState = new NormalShipState();
m_CurrentState.Execute(this);
}
public void Normalize()
{
m_CurrentState = new NormalShipState();
m_CurrentState.Execute(this);
}
public void TriggerRedAlert()
{
m_CurrentState = new AlertShipState();
m_CurrentState.Execute(this);
}
public void DisableShip()
{
m_CurrentState = new DisabledShipState();
m_CurrentState.Execute(this);        
}
public void LogStatus(string status)
{
Debug.Log(status);
}
}

我不明白当变量m_CurrentState被"重新初始化"时会发生什么。所以我们在清醒中,我们把我们的m_CurrentState作为一个正常的船态。但是当我们请求更改状态时,这个变量"m_CurrenState"到底会发生什么? 我已经读过关于垃圾收集和他的所有阶段,他将释放死物,为其他物体腾出位置。但是当我们进行new((调用时,这个"m_CurrentState"会发生什么?

  1. 旧记忆会怎样?它会被垃圾收集器收集吗?

  2. 每次我请求更改状态时,它都会进行新的内存分配,并可能导致内存溢出?

如果没有对m_CurrentState先前引用的对象的其他引用,则该对象将被垃圾回收,如果有,则不会。

它与任何其他对象相同,它没有特殊的垃圾回收规则,因为它是一个接口。

最新更新