0

In the context of the design pattern state. What are the pros and cons of embedding the StateContext as additional method argument in State?

To make it clearer:

public void handle(Object obj); vs. public void handle(StateContext context, Object obj);


Refactoring the context into the parameter list, instead of keeping it as class member, would increase low coupling and enhance the reuse capabilities of the object. At the same time, having the context as member would reduce the size of the parameter list and also benefit to having high cohesion.

But having a decoupled context introduces a new class of errors, where global state inconsistencies can occurr, when multiple context instances are used.

I began thinking about this problem, as I thought about a clean way to switch states.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
mike
  • 4,929
  • 4
  • 40
  • 80

1 Answers1

1

From the Gang of Four book,

The State pattern does not specify which participant defines the criteria for state transitions. If the criteria are fixed, then they can be implemented entirely in the Context.

In other words, if the State instances do not need to participate in State transitions, the transition logic can be centralized in the Context and the States can remain decoupled from each other. (This is the case where the handle() method doesn't need a Context.)

It is generally more flexible and appropriate, however, to let the State subclasses themselves specify their successor state and when to make the transition. This requires adding an interface to the Context that lets State objects set the Context's current state explicitly.

If the Context passes itself to each State, one State can explicitly transition to the next through a callback method on the Context. Essentially, the States form a singly-linked list. (This is the case where the handle() method requires a Context.)

Decentralizing the transition logic in this way makes it easy to modify or extend the logic by defining new State subclasses. A disadvantage of decentralization is that one State subclass will have knowledge of at least one other, which introduces implementation dependencies between subclasses.

jaco0646
  • 15,303
  • 7
  • 59
  • 83
  • *if the State instances do not need to participate in State transitions, the transition logic can be centralized in the Context*, i.e. if the states and their transitions can be modelled as [DFA](https://en.wikipedia.org/wiki/Deterministic_finite_automaton). Thx, didn't think about that. – mike Apr 12 '16 at 15:06