繼承,調用方法先後加加強邏輯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修飾