内容简介:版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/thc1987/article/details/83001079
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/thc1987/article/details/83001079
题目:有一个接口Processor,分别被ServiceA和ServiceB实现。
interface Processor { void process(); } class ServiceA implements Processor { @Override public void process() { System.out.println("run ServiceA..."); } } class ServiceB implements Processor { @Override public void process() { System.out.println("run ServiceB..."); } }
要求前10次由ServiceA运行,超过10次后自动切换成ServiceB运行。
代码如下:
interface Processor { void process(); } class ServiceA implements Processor { @Override public void process() { System.out.println("run ServiceA..."); } } class ServiceB implements Processor { @Override public void process() { System.out.println("run ServiceB..."); } } public class DynamicRun { static class ProcessRunner implements Processor { private DelegateProcess target; private int runCount; private ServiceA defaultProcessor = new ServiceA(); @Override public void process() { int count = ++this.runCount; System.out.println("默认运行次数:" + count); if (count >= 10) { System.out.println("默认运行次数到达10次,切换为ServiceB运行"); // 将真正processor改为ServiceB this.target.setDelegate(new ServiceB()); } defaultProcessor.process(); } public void setTarget(DelegateProcess target) { this.target = target; } } static class DelegateProcess implements Processor { private Processor delegate; private DelegateProcess(Processor delegate) { this.delegate = delegate; } @Override public void process() { delegate.process(); } public void setDelegate(Processor delegate) { this.delegate = delegate; } } public static void main(String[] args) { // 拿到这个processor,可在其它地方运行,不受约束 Processor processor = buildProcessor(); for (int i = 0; i < 15; i++) { processor.process(); } } private static Processor buildProcessor() { ProcessRunner processRunner = new ProcessRunner(); DelegateProcess delegateProcess = new DelegateProcess(processRunner); processRunner.setTarget(delegateProcess); return delegateProcess; } }
此方式在JDK中也有出现,可以参考 sun.reflect.ReflectionFactory.newMethodAccessor()
方法。该方法在使用 Method.invoke()
时用到。代码片段如下:
NativeMethodAccessorImpl var2 = new NativeMethodAccessorImpl(var1); DelegatingMethodAccessorImpl var3 = new DelegatingMethodAccessorImpl(var2); var2.setParent(var3);
以上所述就是小编给大家介绍的《动态改变执行方法》,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对 码农网 的支持!
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。