Shiro Filter中利用Callable和Runnable的委派模式
Callable模式
package com.wjz.core; import java.util.ArrayList; import java.util.List; import java.util.concurrent.Callable; public class SubjectCallable<V> implements Callable<V> { private Callable<V> delegate; private List<V> resouces; public SubjectCallable(Callable<V> delegate) { this.delegate = delegate; } @Override public V call() throws Exception { preCall(); V v = doCall(this.delegate); postCall(v); return v; } private void add(V v) { resouces.add(v); } private void postCall(V v) { if (v == null) { throw new RuntimeException(); } add(v); } private void preCall() { if (resouces == null) { resouces = new ArrayList<V>(); } } private V doCall(Callable<V> target) throws Exception { return target.call(); } }
Runnable模式
package com.wjz.core; public class SubjectRunnable<V> implements Runnable { private Runnable delegate; @Override public void run() { doRun(this.delegate); } private void doRun(Runnable target) { target.run(); } }
Demo
package com.wjz.core; import java.util.concurrent.Callable; public class DelegatingSubject { public <V> V execute(Callable<V> delegate) { Callable<V> associated = associateWith(delegate); try { return associated.call(); } catch (Exception e) { throw new RuntimeException(); } } private <V> Callable<V> associateWith(Callable<V> delegate) { return new SubjectCallable<>(delegate); } }