代理模式
代理模式就是给某一个对象创建一个代理对象,有这个代理对象控制对原对象的引用,而创建这个代理对象后可以在调用原对象时增加一些额外的操作。
普通代理
接口类Sourceable.java
public interface Sourceable {
public void method();
}
原对象类Sourceable.java
public class Source implements Sourceable {
@Override
public void method() {
System.out.println("the original method!");
}
}
代理类Proxy.java
public class Proxy implements Sourceable {
private Source source;
public Proxy(){
super();
this.source = new Source();
}
@Override
public void method() {
before();
source.method();
after();
}
private void after() {
System.out.println("after proxy!");
}
private void before() {
System.out.println("before proxy!");
}
}
测试类
public class ProxyTest {
public static void main(String[] args) {
Sourceable source = new Proxy();
source.method();
}
}
动态代理
动态代理不需要对每个类,都重写代理类。
JDK的java.lang.reflect包下有个Proxy类,它是构造代理类的入口。newProxyInstance方法就是创建代理对象的方法。
newProxyInstance有三个参数:ClassLoader,用于加载代理类的Loader类,通常这个Loader和被代理的类是同一个Loader类;Interfaces,是要被代理的那些接口;InvocationHandler,用于执行出了被代理接口中方法之外的用户自定义操作,它也是用户需要代理的最终目的。
接口类Calculator.java
package dproxy;
public interface Calculator {
int add(int a,int b);
}
接口实现类CalculatorImpl.java
package dproxy;
public class CalculatorImpl implements Calculator{
@Override
public int add(int a, int b) {
int result = a+b;
System.out.println("计算结果:"+result);
return result;
}
}
调用前后操作类LogHandler.java
package dproxy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
public class LogHandler implements InvocationHandler{
Object obj;
public LogHandler(Object obj){
this.obj = obj;
}
public Object invoke(Object obj1, Method method, Object[] args)
throws Throwable {
this.doBefore();
Object o = method.invoke(obj, args);
this.doAfter();
return o;
}
public void doBefore(){
System.out.println("------调用代理类前 ,before-------");
}
public void doAfter(){
System.out.println("------调用代理类前 ,after-------");
}
}
测试类
package dproxy;
import java.lang.reflect.Proxy;
public class Test {
public static void main(String[] args){
Calculator calculator = new CalculatorImpl();
LogHandler lh = new LogHandler(calculator);
Calculator proxy = (Calculator) Proxy.newProxyInstance(calculator.getClass().getClassLoader(), calculator.getClass().getInterfaces(), lh);
proxy.add(1, 1);
}
}