+1

circular dependency in state patrern

NeilTeng 2 months ago updated by Daryl Stark 1 month ago 1

In the structure,context refers to state while the state also refers to the context owning it. 
Similarly, in the pseudo code, the player owns the state but at the same time the state also refers to the player?

Could you help me to understand is this the right composition? and how does the gabage collection work here? (I know in some modern like swift can let you annoate the order but that does not mean we should have circular dependency here)

+1

I struggle with the same thing, but I think the key is to write to interfaces and not to implementations. I'm not sure what programming language you're using, but in Python it would something like this:

from abc import ABC, abstractmethod

class AppInterface(ABC):
    def __init__(self, state: 'StateInterface') -> None:
        self._state: StateInterface = state

class StateInterface:
    def __init__(self, app: AppInterface) -> None:
         self._app = app

Then, you can use your implementation to work with these interfaces:

class MyApp(AppInterface):
    ...

class FirstState(StateInterface):
    ...

class SecondState(StateInterface):
    ...

class ThirdState(StateInterface):
    ...

if __name__ == '__main__':
    third_state = ThirdState()
    second_state = SecondState()
    second_state.set_next(second_state)
    first_state = FirstState()
    first_state.set_next(second_state)
    app = MyApp(state=first_state)

Does this help you?