動態代理(JAVA設計模式)

來源:互聯網
上載者:User

靜態代理只能對實現指定介面的類進行代理,當我想為多個介面中的多個方法前後添加邏輯的時候使用靜態代理會變得十分麻煩。

動態代理可以滿足我的要求。

使用JDK的動態代理十分簡單。

需要用到的類有:

java.lang.reflect.InvocationHandler

java.lang.reflect.Proxy

java.lang.reflect.Method

public interface Moveable {    public void run();}public interface Stopable {    public void stop();} 

//需要代理的類public class Car implements Moveable,Stopable{    public void run() {        System.out.println("car move");    }    public void stop() {        System.out.println("car stop");    }}

//實現InvocationHandler介面,定義需要添加的邏輯,可以是時間記錄,日誌記錄,事務等。class LogHander implements InvocationHandler{Object obj;public LogHander(Object obj) {this.obj = obj;}public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {System.out.println(" log hander start...");Object result =  method.invoke(obj, args);System.out.println(" log hander end...");return result;}}

public class Client {public static void main(String[] args) {            Car car = new Car();            LogHander h = new LogHander(car);            Object proxyCar = java.lang.reflect.Proxy.newProxyInstance(car.getClass().getClassLoader(), new Class[] { Moveable.class,                    Stopable.class }, h);            Moveable m = (Moveable) proxyCar;            m.run();            Stopable s = (Stopable) proxyCar;            s.stop();    }}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.