package com.DynamicProxy3; /** * 动态代理: 抽象角色(公共接口) * * @author DW * */ public interface DoSomething { public void working(String work); }
package com.DynamicProxy3; /** * 动态代理: 真实角色 * * @author DW * */ public class Man implements DoSomething { private String name; public Man(String name) { this.name = name; } @Override public void working(String work) { System.out.println(this.name + "在" + work); } }
package com.DynamicProxy3; /** * 动态代理: 真实角色 * * @author DW * */ public class Woman implements DoSomething { private String name; public Woman(String name) { this.name = name; } @Override public void working(String work) { System.out.println(this.name + "在" + work); } }
package com.DynamicProxy3; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; /** * 动态代理: 代理角色 * * @author DW * */ public class People implements InvocationHandler { private Object object; public People(Object object) { this.object = object; } /** * 动态接受不同的真实角色对象 * @param object */ public void setObject(Object object) { this.object = object; } public static Object factory(Object object) { InvocationHandler handler = new People(object); // 动态生成一个代理 return Proxy.newProxyInstance(object.getClass().getClassLoader(), // 真实对象的类加载器 object.getClass().getInterfaces(), // 真实对象实现的所有接口(数组) handler // 代理对象, ); } /** * 代理角色类实现了InvocationHandler接口的invoke方法, 当factory方法每次调用后, 都动态生成一个代理实例, * 当该代理实例引用在外部调用working()方法时, 实际都是在调用本方法; 并通过java底层传参利用反射机制, 将该代 * 理角色接收的真实角色的working方法通过参数2传递进来, working方法的参数则通过参数3传递进来... * */ @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { // 实际形态:handler引用指向的代理角色对象接受的真实用户的working方法 return method.invoke(this.object, args); } }
package com.DynamicProxy3; /** * 动态代理: 测试 * * @author DW * */ public class DynamicProxyTest { public static void main(String[] args) { DoSomething doSomething = (DoSomething)People.factory(new Man("张三")); doSomething.working("狩猎"); // 张三在狩猎 doSomething = (DoSomething)People.factory(new Man("李四")); doSomething.working("劈柴"); // 李四在劈柴 doSomething = (DoSomething)People.factory(new Woman("翠花")); doSomething.working("做酸菜"); // 翠花在做酸菜 } }