JDK动态代理简单使用

JDK动态代理简单使用,第1张

JDK动态代理简单使用 1、静态代理的简单使用
public interface UsbSell {

    float sell(int amount);

}
public class UsbKingFactory implements UsbSell {
    @Override
    public float sell(int amount) {
        //设置售卖的价格
        return 85.0f;
    }
}
public class Business1 implements UsbSell {

    //声明 商家代理的厂商是谁
    private UsbKingFactory usbKingFactory = new UsbKingFactory();

    @Override
    public float sell(int amount) {
        //告诉厂家需要几个
        //目标类的方法
        float price = usbKingFactory.sell(amount);
        //商家进行加价
        //商家对除了厂商之外的,进行的一些 *** 作就属于增强功能
        price = price+(25*amount);
        //最终的价格
        return price;
    }
}
public class ShopMain {

    public static void main(String[] args) {
        Business1 business1 = new Business1();
        float price = business1.sell(1);
        System.out.println("通过商家1,购买的价格为:"+price);
    }

}
2、动态代理
public interface UsbSell {

    float sell(int amount);

}
public class UsbKingFactory implements UsbSell {
    @Override
    public float sell(int amount) {
        //设置售卖的价格
        //目标方法
        System.out.println("目标类中,执行sell目标方法");
        return 85.0f;
    }
}
public class MySellHandler implements InvocationHandler {

    private Object target = null;

    //动态代理:目标对象是活动的,不是固定的,需要传入进来
    //传入是谁,就给谁创建代理
    public MySellHandler(Object target) {
        //给目标对象赋值
        this.target = target;
    }

    
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //原来静态代理中实现的方法,在invoke方法中实现
        Object res = null;
        //执行目标方法
        res = method.invoke(target, args);
        //执行完目标方法后,做的一系列 *** 作都是增强的意思
        if (res != null) {
            Float price = (Float) res;
            price = price + 25;
            res = price;
        }
        System.out.println("商家返利.....");
        return res;
    }
}
public class ShopMain {

    public static void main(String[] args) {
        //1、创建目标对象
        UsbSell factory = new UsbKingFactory();
        //2、创建InvocationHandler对象
        InvocationHandler handler = new MySellHandler(factory);
        //3、创建代理对象
        //ClassLoader loader:类加载器,负责向内存中加载对象,目标对象的类加载器
        //Class[] interfaces:目标对象实现的接口
        //InvocationHandler h:代理类完成的功能
        //返回一个代理类
        UsbSell proxy = (UsbSell) Proxy.newProxyInstance(
                factory.getClass().getClassLoader(),
                factory.getClass().getInterfaces(),
                handler);
        //4、通过代理执行方法
        System.out.println("jdk动态代理创建的对象" + proxy.getClass().getName());
        float price = proxy.sell(1);
        System.out.println("通过动态代理对象,调用方法:" + price);
    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5574253.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-14
下一篇 2022-12-14

发表评论

登录后才能评论

评论列表(0条)

保存