State pattern is useful while parsing String. A state means a part of work, like a method. When you parse some words from the string you will change the state into a new one
这是什么意思?我真的很困惑。
我有一个格式为“OPERATOR OBJECT [FILTER] [VALUES]”的字符串 在解析查询时,您应该使用状态模式。有四种状态:OPERATOR、OBJECT、FILTER 和 VALUES”
最佳答案
我认为你引用的作者可能指的是类似于自动机理论的接受器,它使用不同的状态来存储当前的匹配进度。为了说明这一点,我将举一个例子。然而,状态并不像方法,但它们以不同的方式实现相同的方法。
/** Accepts strings which contain SO */
class Acceptor {
private enum State {
NOTHING_YET {
@Override
State nextState( char c ) {
if(c == 'S') {
return FOUND_S;
} else {
return NOTHING_YET;
}
}
},
FOUND_S {
@Override
State nextState( char c ) {
if(c == 'O') {
return FOUND_SO;
} else if(c == 'S') {
return FOUND_S;
} else {
return NOTHING_YET;
}
}
},
FOUND_SO {
@Override
State nextState( char c ) {
return FOUND_SO;
}
};
abstract State nextState( char c );
}
boolean accept( String word ) {
State current = State.NOTHING_YET;
for(char c : word.toCharArray()) {
current = current.nextState( c );
}
return current == State.FOUND_SO;
}
}
关于java - 解析字符串中的状态模式用法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10480279/