vendredi 11 octobre 2019

State Design Pattern with Interfaces

I'm reading a book with Design Patterns for Unity and I learned about "State Pattern". The curios thing for me is that it the first time when I saw this pattern used with Interfaces. He makes all states using interfaces.

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);
    }
}

I don't understand exactly what happens when the variable m_CurrentState is "re-initialized". So we in Awake we make our m_CurrentState as a NormalShipState. But when we request a change of state this variable "m_CurrenState" what happens exactly? I have read about Garbage Collection and all of his stages and that he will released the dead objects making place for other objects. But what happens with this "m_CurrentState" when we make new() call?

  1. What happens with the old memory? It will be collected by Garbage Collector?

  2. It makes a new memory allocation everytime I request a change of state and can cause memory overflow?

Aucun commentaire:

Enregistrer un commentaire