非常巧妙的一个使用枚举的例子.原文见[url=http://www.javacodegeeks.com/2011/07/java-secret-using-enum-to-build-state.html]这里[/url]
interface Context {
ByteBuffer buffer();
State state();
void state(State state);
}
interface State {
/**
* @return true to keep processing, false to read more data.
*/
boolean process(Context context);
}
enum States implements State {
XML {
public boolean process(Context context) {
if (context.buffer().remaining() < 16) return false;
// read header
if(headerComplete)
context.state(States.ROOT);
return true;
}
}, ROOT {
public boolean process(Context context) {
if (context.buffer().remaining() < 8) return false;
// read root tag
if(rootComplete)
context.state(States.IN_ROOT);
return true;
}
}
}
public void process(Context context) {
socket.read(context.buffer());
while(context.state().process(context));
}
使用枚举实现状态机
本文介绍了一种利用Java枚举来构建状态机的方法。通过定义一个枚举类型并实现状态接口,每个枚举值代表一种状态,并可以定义该状态下的处理逻辑。此方法简洁高效,易于理解和维护。
5931

被折叠的 条评论
为什么被折叠?



