继承,调用方法先后加加强逻辑java
聚合 - 静态代理ide
持有被代理类对象 或者接口this
可经过嵌套实现代理的组合 和 装饰器模式很像spa
package club.interview.design_pattern.chapt6_proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * @author QuCheng on 2020/6/15. */ public interface Vegetable { void growUp(); class Cabbage implements Vegetable { @Override public void growUp() { System.out.println("卷心菜慢慢长大"); } } class LogProxy implements InvocationHandler { Object o; public LogProxy(Object o) { this.o = o; } public static Object getProxy(Object object) { System.getProperties().setProperty("sun.misc.ProxyGenerator.saveGeneratedFiles", "true"); return Proxy.newProxyInstance(object.getClass().getClassLoader(), object.getClass().getInterfaces(), new LogProxy(object)); } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("good goods study"); Object invoke = method.invoke(o, args); System.out.println("day day up"); return invoke; } public static void main(String[] args) { Vegetable v = (Vegetable) LogProxy.getProxy(new Cabbage()); v.growUp(); } } }
package club.interview.design_pattern.chapt6_proxy; import net.sf.cglib.proxy.Enhancer; import net.sf.cglib.proxy.MethodInterceptor; import net.sf.cglib.proxy.MethodProxy; import java.lang.reflect.Method; /** * @author QuCheng on 2020/6/15. */ public class CabbageCglib { public void growUp() { System.out.println("卷心菜慢慢长大"); } static class LogProxyCglib implements MethodInterceptor { @SuppressWarnings("unchecked") static <T> T getProxy(T o) { Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(o.getClass()); enhancer.setCallback(new LogProxyCglib()); return (T) enhancer.create(); } @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println("good good study"); // invokeSuper not invoke Object invoke = methodProxy.invokeSuper(o, objects); System.out.println("day day up"); return invoke; } } public static void main(String[] args) { CabbageCglib cabbageCglib = LogProxyCglib.getProxy(new CabbageCglib()); cabbageCglib.growUp(); } }
jdk 代理
优势:jdk原生,可代理有接口实现的类code
缺点:代理类必须实现接口对象
cglibblog
优势:继承
被代理类无需实现接口接口
实现简单,无需聚合
缺点:由于是采用继承,被代理类不能被final修饰