代理模式

来源:互联网 发布: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();}}

使用动态代理,是使用反射机制形成的。


 

 

原创粉丝点击