public class Handler implements InvocationHandler
{
HandlerState state = new NormalState();
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// Make all method calls to the state object, not this object.
this.state.doStuff();
return this.state.doOtherStuff();
}
public void switchToErrorState(){
this.state = new ErrorState();
}
}
public interface HandlerState
{
public void doStuff();
public String doOtherStuff();
}
public class ErrorState implements HandlerState
{
@Override
public void doStuff() {
// Do stuff we do in error mode
}
@Override
public String doOtherStuff() {
// Do other error mode stuff.
return null;
}
}
public class NormalState implements HandlerState
{
@Override
public void doStuff() {
// Do normal stuff
}
@Override
public String doOtherStuff() {
// Do normal other stuff
return null;
}
}
# 1 楼答案
我认为您需要保留相同的调用处理程序,但要让它改变其行为。如果在调用处理程序中使用状态模式,这将更接近您所寻找的: