静态代理
- 真实角色
- 代理角色 :持有真实角色的引用
- 二者实现相同的接口
最近在北京租房,举一个租房的例子
创建一个租房的接口,里面有租房方法
public interface Rent{
//公共方法租房
void renting();
}
真实角色
class You implements Rent{
@Override
//租房
public void renting(){
System.out.println("我要租房子");
}
}
代理角色,中介公司
class Agency implements Rent{
Rent you;
public Agency(){
}
public Agency(Rent you){
this.you = you;
}
//租房前要做的
private void before(){
System.out.println("找中介公司");
}
private void after(){
System.out.println("交房租");
}
@Override
public void renting(){
before();
you.renting();
after();
}
}
测试
public class StaticProxy {
public static void main(String[] args) {
//创建真实角色
You you = new You();
//创建代理角色+真实角色的引用
Agency agency = new Agency(you);
agency.renting();
}
}
输出:
找中介公司
我要租房子
交房租
动态代理
使用java.lang.reflect.Proxy实现
Rent接口
public interface Rent {
public void renting();
}
真实角色
public class You implements Rent {
public void renting() {
System.out.println("我要租房子");
}
}
代理角色,中介公司
public class ProxyHandler implements InvocationHandler{
private Object tar;
//绑定委托对象,并返回代理类
public Object bind(Object tar){
this.tar = tar;
//绑定该类实现的所有接口,取得代理类
return Proxy.newProxyInstance(tar.getClass().getClassLoader(),
tar.getClass().getInterfaces(),
this);
}
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result = null;
//这里可以进行AOP编程
//在调用具体函数方法前,执行功能处理
System.out.println("找中介公司");
result = method.invoke(tar,args);
//在调用具体函数方法后,执行功能处理
System.out.println("交房租");
return result;
}
}
测试
public class TestProxy {
public static void main(String[] args) {
ProxyHandler proxyHandler = new ProxyHandler();
Rent rent = (Rent) proxyHandler.bind(new You());
rent.renting();
}
}
输出:
找中介公司
我要租房子
交房租