Java 代理模式

代理模式

代理模式 實現(xiàn)邏輯和實現(xiàn)的解耦

代理模式 為了提供額外的的操作,插入用來代替實際對象的對象。這些操作通常涉及與實際對象通信,代理充當中間人的角色

  • 接口
/**
 * 接口
 */
public interface Interface {
    void doSomething();
    void somethingElse(String arg);
}
  • 實際對象
/**
 * 實際對象
 */
public class RealObject implements Interface {
    public void doSomething() {
        System.out.println("doSomething");
    }

    public void somethingElse(String arg) {
        System.out.println("somethingElse" + arg);
    }
}

  • 代理對象
/**
 * 代理對象
 */
public class Proxy implements Interface {
    private Interface proxied;

    public Proxy(Interface proxied) {
        this.proxied = proxied;
    }

    public void doSomething() {
        System.out.println("Proxy doSomething");
        proxied.doSomething();
    }

    public void somethingElse(String arg) {
        System.out.println("Proxy somethingElse" + arg);
        proxied.somethingElse(arg);
    }
}
  • 測試
    /**
     * 測試代理,比較原對象與代理對象
     *
     * @param args
     */
    public static void main(String[] args) {
        Interface iface = new RealObject();
        iface.doSomething();
        iface.somethingElse("bonobo");

        Interface iface2 = new Proxy(iface);
        iface2.doSomething();
        iface2.somethingElse("bonobo");
    }

動態(tài)代理

Java動態(tài)代理可以動態(tài)創(chuàng)建代理并動態(tài)處理對所代理的方法的調(diào)用

在動態(tài)里上所做的所有調(diào)用都會被重定向到單一的調(diào)用處理器上,它的工作是揭示調(diào)用的類型并確定對應的對策

  • 動態(tài)代理
public class DynamicProxyHandler implements InvocationHandler {
    private Object proxied;

    public DynamicProxyHandler(Object proxied) {
        this.proxied = proxied;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("**** proxy:" + proxy.getClass() + ".method: " + method + ".args: " + args);
        if (args != null) {
            for (Object arg : args) {
                System.out.println("    " + args);
            }
        }
        return method.invoke(proxied, args);
    }
}
  • 測試
    public static void main(String[] args){
        RealObject real = new RealObject();
        real.doSomething();
        real.somethingElse("bonobo");

        Interface proxy = (Interface) Proxy.newProxyInstance(
                Interface.class.getClassLoader(),
                new Class[]{Interface.class},
                new DynamicProxyHandler(real));
        proxy.doSomething();
        proxy.somethingElse("bonobo");

    }
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容