代理模式是一種設(shè)計模式,簡單說即是在不改變源碼的情況下,實現(xiàn)對目標(biāo)對象的功能擴(kuò)展。
目標(biāo):在eat方法執(zhí)行的前后增加業(yè)務(wù)邏輯
準(zhǔn)備工作
先準(zhǔn)備三個基礎(chǔ)類
public interface Person { void eat();}/** * 實現(xiàn)了Person接口 */public class OnePerson implements Person{ @Override public void eat() { System.out.println(“我吃飯了”); }}/** * 未實現(xiàn)任何接口 */public class User { public void eat(){ System.out.println(“用戶正在吃飯”); }}
靜態(tài)代理
優(yōu)點:直觀、簡單、效率高
缺點:代理對象必須提前寫出,如果接口層發(fā)生了變化,代理對象的代碼也要進(jìn)行維護(hù)
public class PersonProxy implements Person { private Person person; public PersonProxy(Person person) { this.person = person; } @Override public void eat() { System.out.println(“飯前先洗手”); this.person.eat(); System.out.println(“飯后百步走”); }}public class Demo { public static void main(String[] args) { Person person = new PersonProxy(new OnePerson()); person.eat(); }}
動態(tài)代理(也叫JDK代理)
缺點:至少包含一個接口
public class JDKDongTaiProxy { public static void main(String[] args) { Person target = new OnePerson(); Person person = (Person) Proxy.newProxyInstance( target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println(“飯前先洗手”); Object result = method.invoke(target, args); System.out.println(“飯后百步走”); return result; } }); person.eat(); }}
Cglib代理
缺點:依賴cglib包
public class MyMethodInterceptor implements MethodInterceptor { @Override public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable { System.out.println(“飯前先洗手”); Object result = methodProxy.invokeSuper(o, objects); System.out.println(“飯后百步走”); return result; }}public class Demo { public static void main(String[] args) { // 沒有實現(xiàn)接口 Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(User.class); enhancer.setCallback(new MyMethodInterceptor()); User user = (User) enhancer.create(); user.eat(); // 實現(xiàn)了接口 enhancer = new Enhancer(); enhancer.setSuperclass(OnePerson.class); enhancer.setCallback(new MyMethodInterceptor()); Person person = (Person) enhancer.create(); person.eat(); }}