代理模式:
静态代理:
接口(真实角色和代理共同享有)
package demo0;
public interface Rent {
public void rent();
}
真实角色
package demo0;
public class Host implements Rent{
@Override
public void rent() {
System.out.println("房东要租房子");
}
}
代理
public class Proxy implements Rent{
private Host host;
public Proxy() {
}
public Proxy(Host host) {
this.host = host;
}
@Override
public void rent() {
seeHosee();
host.rent();
fare();
}
public void seeHosee(){
System.out.println("看房子");
}
public void fare(){
System.out.println("收租金");
}
}
客户端
public class Client {
public static void main(String[] args) {
Host host=new Host();
Proxy proxy=new Proxy(host);
proxy.rent();
}
}
优点:使真实角色更加纯粹,不需要考虑公共的事情
公共的事情由代理完成,实现业务的分工
集中管理,方便操作
缺点:每个真实角色都会对应一个代理,代码量会翻倍
加深理解:(为了尽量不修改源代码,所以增加了 代理)
动态代理:
我不是很明白,但是好像这玩意是固定的
代理需要真实对象,方法
然后就是代理类 ProxyInvocationHandler.java
package demo2;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Rent rent;
//传入真实对象(要代理的对象)
public void setRent(Rent rent) {
this.rent = rent;
}
//生成代理类
//第二个参数:获取要代理的角色,也就是方法的接口 class.interface
//之前都是一个角色,现在可以代理一类角色
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), rent.getClass().getInterfaces(),this);
}
//proxy : 代理类 method : 代理类的调用处理程序的方法对象.
//处理代理实例方法并返回结果
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
seeHouse();
//核心:利用反射实现
Object result= method.invoke(rent,args);
fare();
return result;
}
public void seeHouse(){
System.out.println("中介带着看房子");
}
public void fare(){
System.out.println("收中介费");
}
}
测试
public class Client {
public static void main(String[] args) {
//真实对象
Host host=new Host();
//代理实例调用处理程序
ProxyInvocationHandler pih = new ProxyInvocationHandler();
pih.setRent(host); //传入真实角色
Rent proxy = (Rent) pih.getProxy(); //动态生成代理类
proxy.rent();
}
}
呃呃,不是很懂,但是格式固定
通用的代理类
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
public class ProxyInvocationHandler implements InvocationHandler {
private Object object;
public void setObject(Object object) {
this.object = object;
}
//生成代理类
public Object getProxy(){
return Proxy.newProxyInstance(this.getClass().getClassLoader(), object.getClass().getInterfaces(),this);
}
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
Object result =method.invoke(object,args);
return null;
}
}
用的时候直接传入真实对象,然后生成动态代理(方法)