import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; //接口 interface MyInterface { public void action(); } // 被代理类 class MyObject implements MyInterface { @Override public void action() { System.out.println("我是被代理类,执行action!"); } } //被代理接口 interface ClothFactory{ public void productCloth(); } //被代理类 class NikeClothFactory implements ClothFactory{ @Override public void productCloth() { System.out.println("我是被代理类,Nike 生产衣服"); } } //实现InvocationHandler接口的子类 class MyInvocationhandler implements InvocationHandler { private Object obj; public void setObject(Object obj) { this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { System.out.println("动态代理类执行,收代理费"); Object returnVal = method.invoke(obj, args); return returnVal; } } //动态代理类 class MyProxy { public static Object getProxyInstance(Object obj, InvocationHandler handler) { return Proxy.newProxyInstance(obj.getClass().getClassLoader(), obj .getClass().getInterfaces(), handler); } } public class TestProxy { /** * @Title: main * @Description: * @param: * @return void * @user: wangzg * @Date:2014-10-27 * @throws */ public static void main(String[] args) { // TODO Auto-generated method stub //被代理类 MyObject myObject = new MyObject(); MyInvocationhandler myInvocationhandler = new MyInvocationhandler(); myInvocationhandler.setObject(myObject); Object myProxy = MyProxy.getProxyInstance(myObject, myInvocationhandler); MyInterface myInterface = (MyInterface)myProxy; myInterface.action(); NikeClothFactory nikeClothFactory = new NikeClothFactory(); myInvocationhandler.setObject(nikeClothFactory); Object myProxyNike = MyProxy.getProxyInstance(nikeClothFactory, myInvocationhandler); ClothFactory clothFactory = (ClothFactory)myProxyNike; clothFactory.productCloth(); } }
时间: 2024-10-13 04:23:10