0

我需要替换 Proxy 对象中的 InvocationHandler 。但是它只有吸气剂,没有二传手。为什么会这样,有什么解决方法吗?

谢谢

4

1 回答 1

0

我认为你需要保持相同的调用处理程序,但让它改变它的行为。如果您在调用处理程序中使用 State 模式,这将更接近您正在寻找的内容:

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;
    }
}
于 2013-11-29T17:02:44.460 回答