在线不卡日本ⅴ一区v二区_精品一区二区中文字幕_天堂v在线视频_亚洲五月天婷婷中文网站

  • <menu id="lky3g"></menu>
  • <style id="lky3g"></style>
    <pre id="lky3g"><tt id="lky3g"></tt></pre>

    我們一定要會寫的三種代理模式

    代理模式是一種設計模式,簡單說即是在不改變源碼的情況下,實現對目標對象的功能擴展。

    目標:在eat方法執(zhí)行的前后增加業(yè)務邏輯

    準備工作

    先準備三個基礎類

    public interface Person { void eat();}/** * 實現了Person接口 */public class OnePerson implements Person{ @Override public void eat() { System.out.println(“我吃飯了”); }}/** * 未實現任何接口 */public class User { public void eat(){ System.out.println(“用戶正在吃飯”); }}

    靜態(tài)代理

    優(yōu)點:直觀、簡單、效率高

    缺點:代理對象必須提前寫出,如果接口層發(fā)生了變化,代理對象的代碼也要進行維護

    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) { // 沒有實現接口 Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(User.class); enhancer.setCallback(new MyMethodInterceptor()); User user = (User) enhancer.create(); user.eat(); // 實現了接口 enhancer = new Enhancer(); enhancer.setSuperclass(OnePerson.class); enhancer.setCallback(new MyMethodInterceptor()); Person person = (Person) enhancer.create(); person.eat(); }}

    鄭重聲明:本文內容及圖片均整理自互聯網,不代表本站立場,版權歸原作者所有,如有侵權請聯系管理員(admin#wlmqw.com)刪除。
    用戶投稿
    上一篇 2022年7月4日 06:38
    下一篇 2022年7月4日 06:39

    相關推薦

    聯系我們

    聯系郵箱:admin#wlmqw.com
    工作時間:周一至周五,10:30-18:30,節(jié)假日休息