代理模式就是控制对象的访问,客户访问代理对象,代理对象找真正的对象做事。包括静态代理,动态代理,虚拟代理,远程代理等。这里就简单些下静态代理和动态代理。
1.创建计算器接口
1 package cn.sp.test4; 2 3 /** 4 * Created by 2YSP on 2017/9/1. 5 */ 6 public interface Calculator { 7 int add(int a,int b); 8 }
2.创建实现类(真正做事的)
1 package cn.sp.test4; 2 3 /** 4 * Created by 2YSP on 2017/9/1. 5 * 实现类 6 */ 7 public class CalculatorImpl implements Calculator { 8 @Override 9 public int add(int a, int b) { 10 return a+b; 11 } 12 }
3.创建其代理对象
1 package cn.sp.test4; 2 3 /** 4 * Created by 2YSP on 2017/9/1. 5 * 静态代理类 6 */ 7 public class CalculatorProxy implements Calculator{ 8 Calculator calculator; 9 10 public CalculatorProxy(Calculator calculator){ 11 this.calculator = calculator; 12 } 13 14 @Override 15 public int add(int a, int b) { 16 //具体执行前可以做的工作 17 int result = calculator.add(a, b); 18 //具体执行后可以做的工作 19 return result; 20 } 21 }
4.测试
1 package cn.sp.test4; 2 3 import jdk.internal.org.objectweb.asm.Handle; 4 5 import java.lang.reflect.Proxy; 6 7 /** 8 * Created by 2YSP on 2017/9/1. 9 */ 10 public class Test { 11 /** 12 * 动态代理测试 13 */ 14 public static void testDynamicProxy(){ 15 Calculator calculator = new CalculatorImpl(); 16 LogHandler logHandler = new LogHandler(calculator); 17 //动态生成代理类 18 Calculator proxy = (Calculator)Proxy.newProxyInstance( 19 calculator.getClass().getClassLoader(), calculator.getClass().getInterfaces(), logHandler); 20 int result = proxy.add(1, 1); 21 System.out.println(result); 22 } 23 24 public static void main(String[] args) { 25 // testDynamicProxy(); 26 testStaticProxy(); 27 } 28 29 /** 30 * 测试静态代理 31 */ 32 public static void testStaticProxy(){ 33 Calculator calculator = new CalculatorImpl(); 34 CalculatorProxy calculatorProxy = new CalculatorProxy(calculator); 35 int i = calculatorProxy.add(1, 2); 36 System.out.println(i); 37 } 38 }
-----------------------------------------------------------------
动态代理部分:
1 package cn.sp.test4; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 6 /** 7 * Created by 2YSP on 2017/9/1. 8 */ 9 public class LogHandler implements InvocationHandler { 10 Object obj; 11 12 LogHandler(Object obj){ 13 this.obj = obj; 14 } 15 @Override 16 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 17 this.doBefore(); 18 Object o = method.invoke(obj, args); 19 this.doAfter(); 20 return o; 21 } 22 23 public void doBefore(){ 24 System.out.println("do this before"); 25 } 26 27 public void doAfter(){ 28 System.out.println("do this after"); 29 } 30 }
动态代理就是利用Java反射在运行时期动态的生产代理类,相比静态代理的好处是不用写很多代理类,很灵活。