【发布时间】:2021-05-27 10:42:17
【问题描述】:
我有一个可以处于不同状态的菜单,所以我决定使用状态模式。在线阅读该模式似乎通常的方法是从另一个状态构造状态,但这对我不起作用,因为我有更复杂的状态需要其他依赖项。我可以在上下文对象中预先创建所有状态,然后从上下文对象中切换状态,但我还需要来自先前状态的一些信息,所以它也会变得混乱。
class State1 {
public State1(Context context, /*some complex constructor*/) {
}
public void Action() {
//Something happend and we want to transition to other state
//Usual way
//this will not work because state1 doesnt have
//dependencies to construct state2
//context->SetState(new State2());
//My current way
//This is better because it works, but you will have to create
//such functions for every state and context object needs to be
//modified if new states are added which is not ideal
context->SetState2(/*something produced by action in state1*/);
}
}
class State2 {
public State2(Context context, /*some complex constructor*/) {
}
}
class Context {
//has current state
}
这是一个糟糕设计的标志吗?
有没有一个干净的解决方案或者我想太多了?
【问题讨论】:
标签: design-patterns state-pattern