JavaWeb19.6【Filter&Listener:利用设计模式之代理模式增强对象的功能】
1 package com.haifei.proxy; 2 3 public interface SaleComputer { 4 5 public String sale(double money); 6 public void show(); 7 }
1 package com.haifei.proxy; 2 3 /** 4 * 真实类 5 */ 6 public class Lenovo implements SaleComputer{ 7 @Override 8 public String sale(double money) { 9 System.out.println("花了" + money + "元买了一台联想电脑"); 10 return "联想电脑"; 11 } 12 13 @Override 14 public void show() { 15 System.out.println("展示电脑"); 16 } 17 }
1 package com.haifei.proxy; 2 3 import java.lang.reflect.InvocationHandler; 4 import java.lang.reflect.Method; 5 import java.lang.reflect.Proxy; 6 7 public class ProxyTest { 8 public static void main(String[] args) { 9 /*//1 创建真实对象 10 Lenovo lenovo = new Lenovo(); 11 //2 调用方法 12 String computer = lenovo.sale(8000); 13 System.out.println(computer);*/ 14 /* 15 花了8000.0元买了一台联想电脑 16 联想电脑 17 */ 18 19 20 //1 创建真实对象 21 Lenovo lenovo = new Lenovo(); 22 23 //2 动态代理增强真实对象 24 /* 25 newProxyInstance三个参数: 26 1. 类加载器:真实对象.getClass().getClassLoader() 27 2. 接口数组:真实对象.getClass().getInterfaces() 28 3. 处理器:匿名内部类new InvocationHandler() 29 */ 30 /*Object proxyLenovo = Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() { 31 @Override 32 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 33 return null; 34 } 35 }); //获取代理对象proxyLenovo*/ 36 //强转为真实类所实现的接口类型 37 SaleComputer proxyLenovo = (SaleComputer)Proxy.newProxyInstance(lenovo.getClass().getClassLoader(), lenovo.getClass().getInterfaces(), new InvocationHandler() { 38 /* 39 代理逻辑编写的方法:代理对象调用的所有方法都会触发该方法执行 40 参数: 41 1. proxy:代理对象 42 2. method:代理对象调用的方法,被封装为method对象 43 3. args:代理对象调用方法时,传递的实际参数 44 */ 45 @Override 46 public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { 47 /*System.out.println("该方法执行了"); 48 System.out.println(method.getName()); 49 System.out.println(args[0]);*/ 50 51 /*Object obj = method.invoke(lenovo, args); //使用真实对象调用该方法 52 return obj;*/ 53 54 if (method.getName().equals("sale")){ 55 double money = (double) args[0]; 56 money = money * 0.85; //代理商吃回扣15%用户实付款,即仅有85%用户实付款到联想手里 57 // Object obj = method.invoke(lenovo, money); 58 // return obj; 59 String obj = (String) method.invoke(lenovo, money); //增强 60 System.out.println("免费送货上门"); //增强 61 return obj + "+鼠标垫+清洁套装+电脑包"; //增强 62 }else { 63 Object obj = method.invoke(lenovo, args); 64 return obj; 65 } 66 } 67 }); 68 69 //3 调用方法 70 String computer = proxyLenovo.sale(8000); 71 System.out.println(computer); 72 proxyLenovo.show(); 73 } 74 }