10

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?

http://en.wikipedia.org/wiki/State_pattern

http://sourcemaking.com/design_patterns/state

jaco0646
  • 15,303
  • 7
  • 59
  • 83
Pup
  • 10,236
  • 6
  • 45
  • 66

1 Answers1

9

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.

cmsjr
  • 56,771
  • 11
  • 70
  • 62
  • 1
    The State class is essentially injected into Context, although in a more complete example the Context class would probably have a constructor that took a parameter of whatever interface State conforms to. The Context isn't really DI for the State because State doesn't depend on Context, State just happens to modify Context. – cmsjr Jul 23 '12 at 05:23