代理模式我還再續

package lyr;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class Demo
{
 public static void main(String[] args)
 {

  // 1.通用的動態代理實現

  CommonInvocationHandler handler = new CommonInvocationHandler();

  Foo f;

  // 2.接口實現1

  handler.setTarget(new FooImpl());

  // 方法參數說明:代理類、代理類實現的接口列表、代理類的處理器

  // 關聯代理類、代理類中接口方法、處理器,當代理類中接口方法被調用時,會自動分發到處理器的invoke方法

  // 如果代理類沒有實現指定接口列表,會拋出非法參數異常

  f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),

  new Class[] { Foo.class },

  handler);

  f.doAction();

  // 3.接口實現2

  handler.setTarget(new FooImpl2());

  f = (Foo) Proxy.newProxyInstance(Foo.class.getClassLoader(),

  new Class[] { Foo.class },

  handler);

  f.doAction();
 }
}
interface Foo
{
    void doAction();
}
class FooImpl2 implements Foo
{
    public FooImpl2()
    {
    }

    public void doAction()
    {
        System.out.println("in FooImp2.doAction()");
    }

}
class FooImpl implements Foo
{
    public FooImpl()
    {
    }

    public void doAction()
    {
        System.out.println("in FooImp1.doAction()");
    }
}
class CommonInvocationHandler implements InvocationHandler
{

    // 動態執行對象,需要回調的對象
    private Object target;

    // 支持構造子注射
    public CommonInvocationHandler()
    {

    }

    // 支持構造子注射
    public CommonInvocationHandler(Object target)
    {
        setTarget(target);
    }

    /**
     *
     * 採用setter方法注射
     *
     * @param target
     *
     */
    public void setTarget(Object target)
    {
        this.target = target;
    }

    /**
     *
     * 調用proxy中指定的方法method,並傳入參數列表args
     *
     */

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
    {
        return method.invoke(target, args);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章