Context Parameter

KarlKnechtel: A recent insight of mine related to StatePattern (or perhaps StrategyPattern too, given the similarity; see the discussion there).

Context: You intend to apply StatePattern to some class in your program. Because StateHasNoState, and you want to avoid LotsOfLittleObjects?, you'd like to be able to use some sort of FlyweightPattern too, so you create one instance of each possible state, and reference them as needed.

Problem: The algorithms applicable for each state need to know something about the containing object - or worse, about objects that the containing object knows about. If you just add a reference back to the containing object in your state object,

Solution: RefactorInterface? of the state so that its methods (but only those which need it) take a ContextParameter - i.e. a reference to the containing "context" as a parameter. So that the parameter can be provided, calling code always sends its messages to the containing object, which delegates to the state, providing a reference to itself when needed.

Side effects:

Examples:


EditText of this page (last edited January 31, 2011) or FindPage with title or text search