将状态上下文作为附加方法参数嵌入到状态中的优缺点是什么?

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

在设计模式的上下文中状态。将 StateContext 作为附加方法参数嵌入 State 的优缺点是什么?

为了更清楚:

public void handle(Object obj); 对比 public void handle(StateContext context, Object obj);


将上下文重构到参数列表中,而不是将其保留为 class 成员,将增加低耦合并增强对象的重用能力。同时,将上下文作为成员可以减少参数列表的大小,也有利于高内聚。

但是具有解耦的上下文会引入新的 class 错误,当使用多个上下文实例时,可能会发生全局状态不一致。

我开始思考这个问题,因为我想到了一种干净的方式来切换状态。

来自四人帮的书,

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.

换句话说,如果State实例不需要参与State转换,转换逻辑可以集中在 Context 中,而 States 可以保持彼此分离。 (这是 handle() 方法不需要 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.

如果Context将自身传递给每个State,一个State 可以通过 Context 上的回调方法显式转换到下一个。本质上,States 形成一个单链表。 (这是 handle() 方法需要 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.