What are the pros and cons of embedding the state context as additional method argument in a state?

左心房为你撑大大i 提交于 2019-12-12 01:39:58

问题


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.


回答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.



来源:https://stackoverflow.com/questions/36548954/what-are-the-pros-and-cons-of-embedding-the-state-context-as-additional-method-a

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!