mardi 25 octobre 2022

Which code is better designed and how to choose

In a game: say there is a treasure hidden behind the stone. When the stone is removed by the player, the treasure will be displayed.

design 1

Stone hold a Treasure

class Treasure
{
    public void SetActive(value: bool) {...}

    public void Init(Stone stone) 
    {
        this.SetActive(false);
    }
}

class Stone
{
    private Treasure treasure; // hold

    public void Remove()
    {
        // ...

        this.treasure.SetActive(true);

        // ...
    }
}

design 2

Stone trigger a event when removed, Treasure ...

class Treasure
{
    public void SetActive(value: bool) {...}

    public void Init(Stone stone) 
    {
        this.SetActive(false);
        stone.OnRemoved += () => { this.SetActive(true); }
    }
}

class Stone
{
    public event Action OnRemoved;

    public void Remove()
    {
        // ...

        this.OnRemoved?.Invoke();

        // ...
    }

}

Which design is better or better?

I'm a little confused and hesitant, are there any good suggestions and rules about these? thanks.

Aucun commentaire:

Enregistrer un commentaire