AbstractObject.java
package cn.foxeye.design.proxy; public abstract class AbstractObject { abstract void eat(); }
RealObject.java
package cn.foxeye.design.proxy; public class RealObject extends AbstractObject { @Override void eat() { System.out.println( " 对象执行吃的操作 " ); } }
ProxyObject.java
package cn.foxeye.design.proxy; public class ProxyObject extends AbstractObject { private RealObject object; public ProxyObject(RealObject object) { this .object = object; } @Override public void eat() { before(); object.eat(); after(); } public void before() { System.out.println( " 做法 " ); } public void after() { System.out.println( " 刷锅 " ); } }
采用Java代理模式,代理类通过调用委托类对象的方法,来提供特定的服务。委托类需要实现一个业务接口,代理类返回委托类的实例接口对象。
按照代理类的创建时期,可以分为:静态代理和动态代理。
静态代理: 指程序员创建好代理类,编译时直接生成代理类的字节码文件。代理类和委托类实现了相同的接口,代理类通过委托类实现了相同的方法。这样就出现了大量的代码重复。而且代理类只能为特定的接口(Service)服务。
动态代理: 在程序运行时,通过反射机制动态生成代理类。代理类需要实现InvocationHandler接口。
Service.java
package cn.foxeye.design.dynamic.proxy; public interface Service { public String getName(); public int total( int a, int b); }
ServiceImpl.java
package cn.foxeye.design.dynamic.proxy; public class ServiceImpl implements Service { private String name; public ServiceImpl(String name) { this .name = name; } public String getName() { return this .name; } @Override public int total( int a, int b) { return a + b; } public boolean isOwner() { if ( " admin " .equals( this .name)) { return true ; } else { return false ; } } }
ProxyService.java
package cn.foxeye.design.dynamic.proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public class ProxyService implements InvocationHandler{ private Object target; public ProxyService(Object target) { this .target = target; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { Object resultObject = null ; if ( ! (target instanceof ServiceImpl)) { System.out.println( " 不能代理该对象 " ); return resultObject; } resultObject = method.invoke(target, args); return resultObject; } public Object getProxyInstance() { return Proxy.newProxyInstance(target.getClass().getClassLoader(), target.getClass().getInterfaces(), this ); } }
Main.java
package cn.foxeye.design.dynamic.proxy; public class Main { public static void main(String[] args) { Service target = new ServiceImpl( " admin " ); ProxyService proxyService = new ProxyService(target); Service service = (Service)proxyService.getProxyInstance(); System.out.println(service.total( 2010 , 203 )); } }