带接口的状态设计模式

State Design Pattern with Interfaces

我正在看 Design Patterns for Unity 的书,我了解了 "State Pattern"。令我感到好奇的是,这是我第一次看到这种模式与接口一起使用。他使所有状态都使用接口。

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 为 "re-initialized" 时会发生什么。所以我们在 Awake 中将 m_CurrentState 作为 NormalShipState。但是当我们请求这个变量 "m_CurrenState" 改变状态时到底发生了什么? 我读过有关垃圾收集及其所有阶段的信息,他将释放死对象,为其他对象腾出空间。但是当我们进行 new() 调用时这个 "m_CurrentState" 会发生什么?

  1. 旧内存会怎样?它会被垃圾收集器收集吗?

  2. 每次我请求状态改变时都会进行新的内存分配,会导致内存溢出吗?

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

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