Java 代理模式

來源:互聯網
上載者:User

標籤:ble   his   額外   dos   turn   中間   stat   ret   tcl   

代理模式

代理模式 實現邏輯和實現的解耦

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

  • 介面
/** * 介面 */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");    }
動態代理

Java動態代理可以動態建立代理並動態處理對所代理的方法的調用

在動態裡上所做的所有調用都會被重新導向到單一的調用處理器上,它的工作是揭示調用的類型並確定對應的對策

  • 動態代理
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");    }

Java 代理模式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.