前言
我们先模拟一个现实场景:我要租房,但是我却找不到房子(毕业季人太多),所以我找了链家帮我找房子,然后链家帮我联系了房主并让我租到了房子…
好,我们来实现一下这个场景:
1.静态代理
我们直接来看代码
1.1、我是租客
public interface Rent{
//我要找房子
public void zhaofang();
}
1.2、房东
public class Fangdong {
public void zufang(){
System.out.println("往外租房子!");
}
}
1.3、代理公司(链家)
public class Proxy implements Rent{
private Fangdong fangdong;
public Proxy() {
}
public Proxy(Fangdong fangdong) {
this.fangdong = fangdong;
}
public void zhaofang() {
dosomething();
fangdong.zufang();
dosomething_2();
}
public void dosomething(){
System.out.println("1、首先,中介要搞一些别的事情...");
}
public void dosomething_2(){
System.out.println("2、然后,中介还要搞一些事情...");
}
}
调用一下:
public class ApplicationMain {
public static void main(String[] args) {
//静态代理
Fangdong fangdong=new Fangdong();
Proxy proxy = new Proxy(fangdong);
proxy.zhaofang();
}
}
运行结果:
1、首先,中介要搞一些别的事情...
往外租房子!
2、然后,中介还要搞一些事情...
我们可以看到,代理类不但实现了租房子这件事,他还从中搞到了一些别的事情…
静态代理虽然效率较高,但其也有不可避免的缺陷。可以看到,客户端在调用代理对象时,使用的是代理对象和被代理对象都实现的一个接口,我们可以将该接口理解为定义了某一种业务需求的实现规范。如果有另外一份业务需求(如进行数据修改),其与当前需求并行的,没有交集的,但是其在进行正常业务之外所做的安全验证工作与当前需求是一致的。
2.动态代理
2.1、租客接口类
public interface Rent {
public void zhaofang();
}
租客实现类
public class RentImpl implements Rent{
public void zhaofang() {
System.out.println("我要租房!");
}
}
2.2、房东类
public class Fangdong {
public void zufang(){
System.out.println("往外租房子!");
}
}
2.3、动态代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyAgent implements InvocationHandler {
// 定义一个代理对象
private Object target;
//使用set 方法导入代理对象
public void setTargent(Object target){
this.target=target;
}
//生成代理对象
public Object getProxy(){
Object proxy=Proxy.newProxyInstance(this.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
return proxy;
}
//处理代理实例,并返回方法
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//中介自己想干嘛干嘛
dosomething();
//动态执行代理对象方法
Object invoke = method.invoke(target, args);
//中介自己想干嘛干嘛
Fangdong fangdong=new Fangdong();
fangdong.zufang();
//中介自己想干嘛干嘛
dosomething_2();
//执行开始
return invoke;
}
public void dosomething(){
System.out.println("1、首先,中介要搞一些别的事情...");
}
public void dosomething_2(){
System.out.println("2、然后,中介还要搞一些事情...");
}
}
运行:
public class ApplicationMain {
public static void main(String[] args) {
//动态代理
RentImpl rentImpl = new RentImpl();
ProxyAgent proxyAgent = new ProxyAgent();
proxyAgent.setTargent(rentImpl);
//必须强转接口类,否则会报错
Rent proxy=(Rent) proxyAgent.getProxy();
proxy.zhaofang();
}
}
运行结果:
1、首先,中介要搞一些别的事情...
我要租房!
往外租房子!
2、然后,中介还要搞一些事情...