1、代理模式
interface BuyerInterface {
String buySomething(String goods);
}
class Buyer implements BuyerInterface {
@Override
public String buySomething(String goods) {
System.out.println("buy a " + goods);
return goods;
}
}
class BuyProxy implements BuyerInterface {
private Buyer trueBuyer;
public BuyProxy(Buyer trueBuyer) {
this.trueBuyer = trueBuyer;
}
@Override
public String buySomething(String goods) {
System.out.println("find true business");
this.trueBuyer.buySomething(goods);
System.out.println("buy a " + goods + " success");
return goods;
}
}
public class PrxyDemo {
public static void main(String[] args) throws Exception {
BuyerInterface buyProxy = new BuyProxy(new Buyer());
buyProxy.buySomething("TV");
System.out.println("**********");
}
2、java 动态代理
2.1 InvocationHandler 实现类告诉程序运行动态生成的代理对象具体要执行什么动作。
“Each proxy instance has an associated invocation handler. When a method is invoked on a proxy instance, the method invocation is encoded and dispatched to the {@code invoke} method of its invocation handler”
class BuyInvocationHandler implements InvocationHandler {
private Object target;
public BuyInvocationHandler(Object target) {
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("find true business");
String result = (String) method.invoke(target, args);
System.out.println("buy a " + args[0] + " success");
System.out.println(result.toString());
return result;
}
}
2.2 动态代理对象生成
InvocationHandler handler = new BuyInvocationHandler(target);
step1:生成字节码文件
Class proxyClazz = Proxy.getProxyClass(BuyerInterface.class.getClassLoader(), BuyerInterface.class);
step2: 获取相应的构造函数类 Constructor的实例
Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
BuyerInterface buyProxy1 = (BuyerInterface)
step:3 通过构造函数实例生成BuyerInterface的实现类实例,即代理对象实例。
constructor.newInstance(handler);
上面的step 1、2、 3 合并:
BuyerInterface buyProxy2 = (BuyerInterface) Proxy
.newProxyInstance(BuyerInterface.class.getClassLoader(), new Class[]{BuyerInterface.class}, handler);
public class PrxyDemo {
public static void main(String[] args) throws Exception {
Buyer target = new Buyer();
InvocationHandler handler = new BuyInvocationHandler(target);
Class proxyClazz = Proxy.getProxyClass(BuyerInterface.class.getClassLoader(), BuyerInterface.class);
Constructor constructor = proxyClazz.getConstructor(InvocationHandler.class);
BuyerInterface buyProxy1 = (BuyerInterface) constructor.newInstance(handler);
buyProxy1.buySomething("TV");
System.out.println("/////////");
BuyerInterface buyProxy2 = (BuyerInterface) Proxy
.newProxyInstance(BuyerInterface.class.getClassLoader(), new Class[]{BuyerInterface.class}, handler);
buyProxy2.buySomething("TV");
}
}