一,先说下静态代理:快520了,小王想去买SK2送女友,但是太贵了,于是拜托在国外的好友小P买,这位小P便是小王的代理。
主体便是以下三个文件,小王和代理类都继承接口,实现具体的方法。
//首先定义公共接口
public interface ICustomer {
void buySK2();
}
//表示小王的类
public class XiaoWang implements ICustomer {
@Override
public void buySK2() {
System.out.println("小王买了Mac");
}
}
//表示小王好友小P的类,是小王的代理,当然也可以说是所有实现ICustomer接口的类的代理
public class CustomerProxy implements ICustomer {
private ICustomer customer;
public CustomerProxy(ICustomer customer) {
this.customer= customer;
}
@Override
public void buySK2() {
System.out.println("代理类要开始买SK2了");
customer.buySK2();
}
}
调用方法很简单
CustomerProxy proxy = new CustomerProxy(new XiaoWang());
proxy.buySK2();
//输出:
//代理类要开始买SK2了
//小王买了SK2
二,继续说动态代理类,小王不仅想买sk2了,还想买mac送女友,如果继续用静态代理,那代理类还需要添加买Mac的方法,这真是太不符合设计思想了,所以需要用动态代理
先看代理类,不管你要添加多少方法,代理类都不会改变:
public class BuyProxy implements InvocationHandler {
private Object delegation;
public BuyProxy(Object delegation) {
this.delegation = delegation;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("小P要去代理"+method.getName());
Object result = method.invoke(delegation,args);
return result;
}
}
再看接口和小王的类:
//相比静态代理买了一个方法
public interface ICustomer {
void buySK2();
void buyMac();
}
//小王的实现类
public class XiaoWang implements ICustomer {
@Override
public void buySK2() {
System.out.println("小王买了SK2");
}
@Override
public void buyMac() {
System.out.println("小王买了Mac");
}
}
最后看下执行代码以及执行结果:
//编译时确定具体的类
ICustomer xiaoWang = new XiaoWang();
//初始化一个代理类
BuyProxy macProxy = new BuyProxy(xiaoWang);
ICustomer customer =(ICustomer)Proxy.newProxyInstance(xiaoWang.getClass().getClassLoader(),
xiaoWang.getClass().getInterfaces(), macProxy);
customer.buySK2();
customer.buyMac();
//打印
//小P要去代理buySK2
//小王买了SK2
//小P要去代理buyMac
//小王买了Mac
可以看到,动态代理类实现了InvocationHandler接口,这个接口只有一个方法
public interface InvocationHandler {
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable;
}
proxy:生成的代理对象;method:要调用的代理对象的方法;调用真实对象某个方法时接受的参数;
未完待续。。。