我真的不明白这个问题。设计模式非常清晰。请参阅Design Patterns book。class SuperState( object ):
def someStatefulMethod( self ):
raise NotImplementedError()
def transitionRule( self, input ):
raise NotImplementedError()
class SomeState( SuperState ):
def someStatefulMethod( self ):
actually do something()
def transitionRule( self, input ):
return NextState()
这是非常普通的样板,用于爪哇、C++、Python(我也肯定其他语言)。
如果您的状态转换规则碰巧是微不足道的,那么有一些优化可以将转换规则本身推送到超类中。
注意,我们需要有前向引用,所以我们按名称引用类,并使用eval将类名转换为实际的类。另一种方法是生成转换规则实例变量而不是类变量,然后在定义所有类之后创建实例。class State( object ):
def transitionRule( self, input ):
return eval(self.map[input])()
class S1( State ):
map = { "input": "S2", "other": "S3" }
pass # Overrides to state-specific methods
class S2( State ):
map = { "foo": "S1", "bar": "S2" }
class S3( State ):
map = { "quux": "S1" }
在某些情况下,您的事件不像测试对象的相等性那么简单,因此更一般的转换规则是使用正确的函数-对象对列表。class State( object ):
def transitionRule( self, input ):
next_states = [ s for f,s in self.map if f(input) ]
assert len(next_states) >= 1, "faulty transition rule"
return eval(next_states[0])()
class S1( State ):
map = [ (lambda x: x == "input", "S2"), (lambda x: x == "other", "S3" ) ]
class S2( State ):
map = [ (lambda x: "bar" <= x <= "foo", "S3"), (lambda x: True, "S1") ]
由于规则是按顺序计算的,因此允许使用“默认”规则。