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

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

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

    代理模式是一種設(shè)計模式,簡單說即是在不改變源碼的情況下,實(shí)現(xiàn)對目標(biāo)對象的功能擴(kuò)展。

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

    準(zhǔn)備工作

    先準(zhǔn)備三個基礎(chǔ)類

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

    靜態(tài)代理

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

    缺點(diǎn):代理對象必須提前寫出,如果接口層發(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代理)

    缺點(diǎn):至少包含一個接口

    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代理

    缺點(diǎn):依賴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) { // 沒有實(shí)現(xiàn)接口 Enhancer enhancer = new Enhancer(); enhancer.setSuperclass(User.class); enhancer.setCallback(new MyMethodInterceptor()); User user = (User) enhancer.create(); user.eat(); // 實(shí)現(xiàn)了接口 enhancer = new Enhancer(); enhancer.setSuperclass(OnePerson.class); enhancer.setCallback(new MyMethodInterceptor()); Person person = (Person) enhancer.create(); person.eat(); }}

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

    相關(guān)推薦

    聯(lián)系我們

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