代理全家福
静态代理
/** * 挣钱 */ public interface MakeMoney { void makeMoney(); }
public class Boss implements MakeMoney { @Override public void makeMoney() { System.out.println("老板想挣钱"); } }
public class Employee implements MakeMoney { private MakeMoney boss; public Employee(MakeMoney boss) { this.boss = boss; } @Override public void makeMoney() { System.out.println("员工在干活"); boss.makeMoney(); } }
Java动态代理
public class Employee implements InvocationHandler { private MakeMoney boss; public Employee(MakeMoney boss) { this.boss = boss; } public MakeMoney proxy() { return (MakeMoney) Proxy.newProxyInstance(boss.getClass().getClassLoader(), boss.getClass().getInterfaces(), this); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("员工干活"); return method.invoke(boss, args); } }
CGLib
public class MakeMoneyImpl implements MethodInterceptor { private MakeMoney target; public MakeMoney getInstance(MakeMoney target) { this.target = target; Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(target.getClass()); enhancer.setCallback(this); return (MakeMoney) enhancer.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, MethodProxy proxy) throws Throwable { System.out.println("员工在干活"); proxy.invokeSuper(obj, args); return null; } }