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 {
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) {
UsbSell factory = new UsbKingFactory();
InvocationHandler handler = new MySellHandler(factory);
UsbSell proxy = (UsbSell) Proxy.newProxyInstance(
factory.getClass().getClassLoader(),
factory.getClass().getInterfaces(),
handler);
System.out.println("jdk动态代理创建的对象" + proxy.getClass().getName());
float price = proxy.sell(1);
System.out.println("通过动态代理对象,调用方法:" + price);
}
}