代理模式
来源:互联网 发布:java中interface用法 编辑:程序博客网 时间:2024/06/05 09:37
一、首先Demo
(一)、公用类
1、接口类HelpServer
package com.yezi.proxy;public interface HelpServer {public void print();}
2、实现类HelpServerImpl
package com.yezi.proxy;public class HelpServerImpl implements HelpServer{@Overridepublic void print() {System.out.println("hello helpServerImpl");}}
(二)、静态代理
1、HelpServerStaticProxy静态代理类
package com.yezi.proxy;public class HelpServerStaticProxy implements HelpServer{private HelpServer helpServer;public HelpServerStaticProxy(HelpServer helpServer) {this.helpServer = helpServer;}@Overridepublic void print() {System.out.println("begin proxy");helpServer.print();System.out.println("end proxy");}}
2、TestStaticProxy,静态代理主函数
package com.yezi.proxy;public class TestStaticProxy {public static void main(String[] args) {HelpServer helpServer = new HelpServerImpl();HelpServerStaticProxy proxy = new HelpServerStaticProxy(helpServer);proxy.print();}}
(三)、动态代理
1、HelpServerProxyFactory使用proxy来代理
package com.yezi.proxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class HelpServerProxyFactory {public static HelpServer getProxy(final HelpServer helpServer) {InvocationHandler handler = new InvocationHandler(){@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {System.out.println("before...");Object object = method.invoke(helpServer,args);System.out.println("end...");return object;}};Class<?> classType = HelpServer.class;return (HelpServer) Proxy.newProxyInstance(classType.getClassLoader(),new Class[]{HelpServer.class},handler);}}
2、TestDnamicProxy动态代理主函数
package com.yezi.proxy;public class TestDnamicProxy {/**动态代理*/public static void main(String[] args) {HelpServer helpServer = new HelpServerImpl();HelpServer proxy = HelpServerProxyFactory.getProxy(helpServer);System.out.println(proxy.getClass().getName());proxy.print();}}
使用动态代理,是使用反射机制形成的。
- 代理模式--动态代理
- 代理模式-静态代理
- 代理模式-静态代理
- 代理模式 & 动态代理
- 代理模式--静态代理
- 代理模式--动态代理
- 代理模式(动态代理)
- 代理模式-动态代理
- 代理模式-动态代理
- 代理模式动态代理
- 代理模式-静态代理
- 代理模式-动态代理
- 代理模式 -动态代理
- 代理模式---动态代理
- 代理模式-动态代理
- 代理模式--静态代理
- 代理模式!
- 代理模式
- WSAEventSelect模型
- 记渣打银行科营中心的面试
- Java问题排查常用linux命令
- instanceof详细用法
- timus1982. Electrification Plan---最小生成树
- 代理模式
- 润乾V5实现关联过滤多选功能
- String方法摘要
- 移植Linux内核和文件系统,超级终端输出出现“[\u@\h \W]#”
- log4j日志组件
- rails 4.0 中 i18n 进行 model 中文化
- Linux的Service之解析
- Python中的random模块
- android SDK安装Failed to fetch URL http://dl-ssl.google.com/android/repository/addons_list-1.xml出错