设计模式:代理模式的理解
什么是代理模式
代理模式(英语:Proxy Pattern)是程序设计中的一种设计模式。
所谓的代理者是指一个类别可以作为其它东西的接口。代理者可以作任何东西的接口:网上连接、存储器中的大对象、文件或其它昂贵或无法复制的资源。(百度百科)
我们先思考一个问题:如何在不修改一个类的方法的情况下,为这个类的方法增加新的功能呢
看如下代码:
public class A {
//在不修改A类的情况为A类的方法增加新的功能
public void Afun(){
System.out.println("A fun()");
}
}
public class B extends A{
public void Afun() {
System.out.println("日志处理");
super.Afun();
System.out.println("事务管理");
}
}
public class Test {
public static void main(String[] args) {
A a = new B();
a.Afun();
}
}
输入结果为:
在这段代码中,类B就充当了代理者,为类A增加了新的功能;但是这并不是严谨意义上的代理模式,因为这里用的是继承,而JAVA是单继承的,此处代码仅作为基础的理解;
真正的代理模式是基于接口的,而JAVA为我们提供的实现代理模式的接口InvocationHandler,具体请看下面代码:
//定义一个接口
public interface Hello {
public void hi(String name);
}
//创建接口的实现类
public class HelloImpl implements Hello{
public void hi(String name) {
System.out.println("原始类的方法");
}
}
//以Spring框架的AOP为例,代理模式用拦截器实现,继承代理接口
public class MyInterceptor implements InvocationHandler{
//被调用的对象
private Object obj;
//构造方法初始化
public MyInterceptor(Object obj){
this.obj = obj;
}
//代理执行方法
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
before();//加入新的功能
method.invoke(obj, args); //调用原始方法
after();//加入新的功能
return null;
}
public void before(){
System.out.println("方法之前加入功能");
}
public void after(){
System.out.println("方法之后加入功能");
}
}
//main方法调用
public class Test {
public static void main(String[] args){
HelloImpl hi = new HelloImpl();
MyInterceptor mi = new MyInterceptor(hi);
Hello h =(Hello)Proxy.newProxyInstance(hi.getClass().getClassLoader(), hi.getClass().getInterfaces(), mi);
h.hi("张三");
}
}
输出结果为: