动态代理模式的使用

package 设计模式;



import java.lang.reflect.InvocationHandler;

import java.lang.reflect.Method;

import java.lang.reflect.Proxy;



//主题接口

interface  Isubject

{

    public void f1();

    public void f2();

}

class Subject implements Isubject

{



    @Override

    public void f1() {

        // TODO Auto-generated method stub

        System.out.println("调用方法1");

        

    }



    @Override

    public void f2() {

        // TODO Auto-generated method stub

        System.out.println("调用方法2");

        

    }

}

//静态代理类的实现

class  StaticProxy implements Isubject

{

    //被代理的对象

    private Isubject real=null;

    public StaticProxy(Isubject real)

    {

        this.real =real;

    }



    @Override

    public void f1() {

        System.out.println("调用前处理");

        real.f1();

        System.out.println("调用后处理");

        

    }



    @Override

    public void f2() {

        // TODO Auto-generated method stub

        System.out.println("调用前处理");

        real.f2();

        System.out.println("调用后处理");

        

    }

    



}

class Handler implements InvocationHandler



{

    private Isubject real=null; //一个实际主题

    public  Handler(Isubject real)

    {

        this.real=real;

    }



    @Override

    public Object invoke(Object proxy, Method method, Object[] args)

            throws Throwable {

        System.out.println("before"+method.getName());

        method.invoke(real, args);

        System.out.println("after"+method.getName());

        return null;

        

    }

}



public class 动态代理2 {



    /**

     * @param args

     */

    public static void main(String[] args) {

        // TODO Auto-generated method stub

        //静态代理类的测试

        Subject sub=new Subject();

        //StaticProxy sp=new StaticProxy(sub);

        //sp.f1();

        ClassLoader loader=sub.getClass().getClassLoader();//获得具体类的加载器

        Class[] interfaces=sub.getClass().getInterfaces();

        Handler h=new Handler(sub);

        Proxy proxy=(Proxy) Proxy.newProxyInstance(loader, interfaces, h);

        ((Isubject) proxy).f1();

        ((Isubject) proxy).f2();

        

        

        

        

        

        

        



    }



}

 

你可能感兴趣的:(动态代理)