代理模式
一:一个类代表另一个类的功能
二:在抽象类与现实类之间添加一个媒介:房东--中介--学生,其中的中介就是代理
三:为其他对象提供一个代理用以控制一个对象的访问
静态代理:
public interface Rent {
void rent();
}
public class Host_A implements Rent {
public void rent() {
System.out.println("包租婆出租房屋100平方米");
}
}
public class Host_B implements Rent{
public void rent() {
System.out.println("包租公偷偷出租房屋200㎡");
}
}
public class Proxy implements Rent {
private Rent r;
public Proxy(int seare) {
if (seare < 100) {
r = new Host_A();
} else {
r = new Host_B();
}
r.rent();
rent();
}
public void rent() {
System.out.println("代租客看房");
}
}
@Test
public void proxy(){
Proxy proxy = new Proxy(90);
}
动态代理:代理类是动态生成的,不是我们直接写的;
一:自己如何创建一个动态代理?
二:一个接口即可
三:如何通过一个接口创建一个动态代理?
基于接口:JDK动态代理
基于类:cglib
java字节码实现:javasist
public interface InvocationHandler
InvocationHandler
is the interface implemented by the invocation handler of a proxy instance.调用代理实例的处理程序需要实现IncocationHandler这个接口:
public class Proxy extends Object implements SerializableProxy
provides static methods for creating dynamic proxy classes and instances, and it is also the superclass of all dynamic proxy classes created by those methods.
Proxy这个类提供了一个静态的方法用于创建动态的类和实例,也是这些方法创建的所有的动态代理类的超类;
例子:
public interface Rent { void rent(); } public class Host implements Rent{ public void rent(){ System.out.println("包租婆出租房屋"); } } public class ProxyIH implements InvocationHandler {
//如果把Rent 改为Object obj; private Rent rent; public void setRent(Rent rent) { this.rent = rent; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
System.out.println("看房子"); return method.invoke(rent, args); } public Object getProxy() { return Proxy.newProxyInstance(Rent.class.getClassLoader(), new Class[]{Rent.class}, this); } } @Test public void getProxy(){ Host host = new Host(); ProxyIH ih = new ProxyIH(); ih.setRent(host); Rent proxy = (Rent)ih.getProxy(); proxy.rent(); }
万能代理:
public class ProxyIH implements InvocationHandler { private Object obj; public void setRent(Object obj) { this.obj = obj; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { return method.invoke(obj, args); } public Object getProxy() { return Proxy.newProxyInstance(this.getClass().getClassLoader(),obj.getClass().getInterfaces(), this); } }