![]()
public interface ISalPc {
public String sail(double price);
}
public class SalPcFactory implements ISalPc{
@Override
public String sail(double price) {
System.out.println("price="+price);
return "原价:"+price;
}
}
/**
* @Author zh
* @Description 动态代理 的处理器
* @Date 2021/12/17
*/
public class DynProxyHandler implements InvocationHandler{
//折扣
private static final double DISCOUNT=0.8;
//1.被代理的对象
private ISalPc salPc ;
public DynProxyHandler(ISalPc salPc) {
this.salPc = salPc;
}
//这里是对原有方法的增强
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//1.如果方法名是 sail的话,我对这个方法进行增强
String name = method.getName();
if (name.equals("sail")) {
double d = (Double) args[0];
//打八折
BigDecimal b1 = new BigDecimal(d + "");
BigDecimal b2 = new BigDecimal(DISCOUNT);
//新价格
BigDecimal multiply = b1.multiply(b2);
Double newprice = Double.valueOf(multiply.toString());
args[0] = newprice;
System.out.println("调用方法前的逻辑.....");
//调用原来的方法
//参数1:实际的被代理 对象, 参数2: 实际的参数列表
String invoke = (String) method.invoke(salPc, args);
System.out.println("调用方法后的逻辑");
return invoke+"跳楼价";
}
return null;
}
}
public class TMain {
public static void main(String[] args) {
//1.被代理类
ISalPc salPc =new SalPcFactory();
//2.处理器
DynProxyHandler handler =new DynProxyHandler(salPc);
//3.创建代理类对象
//参数1: 被代理 类的类加载 器:
//参数2: 获取接口列表
//参数3: 处理器
ISalPc o = (ISalPc) Proxy.newProxyInstance(
salPc.getClass().getClassLoader(),
salPc.getClass().getInterfaces(),
handler
);
//代理类对象增强后的方法:
String sal = o.sail(10.0);
System.out.println(sal);
}
}