版权声明:本文为博主原创文章,未经博主允许不得转载。 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);