设计模式之代理模式 proxy

来源:互联网 发布:2017交通安全事故数据 编辑:程序博客网 时间:2024/06/03 16:37
代码下载:http://download.csdn.net/detail/jzp12/4371044

1)基本概念:
在 Gof 的书中对Proxy模式的目的给定为:为其它的物件提供一种代理,以控制对这个物件的访问。由这句话所延伸出来的意思是,根据您的目的不同,您的代理物件将负有不同的责任,因为产生多种不同的代理情况。代理模式分为静态代理动态代理

2)相关类及其方法

java.lang.reflect.Proxy
Proxy 提供用于创建动态代理类和实例的静态方法.
newProxyInstance()
返回一个指定接口的代理类实例,该接口可以将方法调用指派到指定的调用处理程序

java.lang.reflect.InvocationHandler
InvocationHandler
是代理实例的调用处理程序 实现的接口。
invoke()
在代理实例上处理方法调用并返回结果。在与方法关联的代理实例上调用方法时,将在调用处理程序上调用此方法。

3)代码分析:
下面的示例重点通过接口、动态代理来分析代理模式,有较为详尽的注释,如需了解静态代理,可以参考下面的文章。
先看一下调用时序图:

register.class
//接口类(抽象角色),注册(可以注册公司、商标)
public interface register {public void excute(String strName);}

registerimpl.class
// 接口实现(真实角色),可理解为工商局(负责可注册公司)
public class registerimpl implements register {@Overridepublic void excute(String strName) {// TODO Auto-generated method stubSystem.out.println(strName + " excutes register work");}}

register2impl.class
// 接口实现(真实角色),可理解为商标局(负责可注册商标)
public class register2impl implements register {@Overridepublic void excute(String strName) {// TODO Auto-generated method stubSystem.out.println(strName + " excutes register work");}}

companyregisterimpl.class
//代理类实现(代理角色),可理解为代理注册公司的代理
import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class companyregisterimpl implements InvocationHandler{private Object m_delegate = null;//@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {// TODO Auto-generated method stub//do some processing before the method invocationSystem.out.println("do some processing before the method invocation");        //invoke the method     Object result = method.invoke(m_delegate, args);     //do some processing after the method invocation     System.out.println("do some processing after the method invocation");  return result;}public Object bind(Object delegate) {this.m_delegate = delegate;return Proxy.newProxyInstance(delegate.getClass().getClassLoader(),delegate.getClass().getInterfaces(), this);}}

clientdemo.class
public class clientdemo {public static void main(String[] args) {//代理注册的代理公司companyregisterimpl companyproxy = new companyregisterimpl();//注册公司register instance = (register) companyproxy.bind(new registerimpl());instance.excute("registerimpl");//注册商标instance = (register) companyproxy.bind(new register2impl());instance.excute("register2impl");}}

输出:
do some processing before the method invocation
registerimplexcute register work
do some processing after the method invocation
do some processing before the method invocation
register2implexcute register work
do some processing after the method invocation

参考:

http://lizwjiang.iteye.com/blog/86389
http://www.cnblogs.com/newspring/archive/2009/08/11/1543881.html
http://hi.baidu.com/malecu/blog/item/45d4952b31bc0e27d52af17a.html

原创粉丝点击