The State Pattern seems to use a circular reference. Why is that okay?
-
22-06-2021 - |
Frage
I'm still trying to understand the dangers of circular references. I often read that they should only be used in rare cases. But, in the canonical State Pattern, the "state" objects need to reference the "context" object in order to cause a transition and the "context" object needs to reference the "state" objects in order to trigger their behaviors.
Isn't this a circular reference? If not, how does it relate to circular references? If so, why is this acceptable?
Lösung
Two objects can operate on each other without necessarily referring to each other. In general a circular reference is a case where Class A and B both have a member variable that refers to the other. As implemented in the Wikipedia article there is no circular reference because while the Context stores a reference to the State, the Context is passed into the State as a parameter to a method, and it falls out of scope when the method finishes executing without the State having stored a reference to it.