代理模式(动态代理)简单通俗易懂的例子

静态代理的缺点:

如果接口中增加方法,所有实现类要实现这个方法外所有代理类也要实现这个方法。

动态代理:

目的:代理类不重写接口的方法,在程序运行中动态绑定要代理的方法;

public interface MoveAble2 {
    void run();
    void use();

}
public class Jeep2 implements MoveAble2 {
    public void run() {
        System.out.println("the jeep running...");
    }

    public void use() {
        System.out.println("the jeep using...");
    }
}
public class CarLogProxy2 implements InvocationHandler {
    private Object object;

    public CarLogProxy2(Object object) {
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("log begin...");
        method.invoke(object);
        System.out.println("log end...");
        return null;
    }
}
public class CarTimeProxy2 implements InvocationHandler {
    private Object object;

    public CarTimeProxy2(Object object) {
        this.object = object;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("time begin....");
        method.invoke(object);
        System.out.println("time end....");
        return null;
    }
}
public class testMain {
    public static void main(String[] args) {
        Jeep2 jeep2=new Jeep2();
        CarTimeProxy2 carTimeProxy=new CarTimeProxy2(jeep2);
        Class<?> cls=jeep2.getClass();
        MoveAble2 moveAble2=(MoveAble2)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), carTimeProxy);

        CarLogProxy2 carLogProxy2=new CarLogProxy2(moveAble2);
        MoveAble2 moveAble3=(MoveAble2)Proxy.newProxyInstance(cls.getClassLoader(), cls.getInterfaces(), carLogProxy2);
        //moveAble3.run();
        moveAble3.use();

    }
}


猜你喜欢

转载自blog.csdn.net/weixin_40839342/article/details/80640180