静态代理与动态代理
静态的代码:
package java2_proxy; interface ClothFactory{ void produceCloth(); } // 代理类 class ProxyClothFactory implements ClothFactory{ private ClothFactory factory; // 用被代理类的对象进行实例化 public ProxyClothFactory(ClothFactory factory) { this.factory = factory; } @Override public void produceCloth() { System.out.println("代理工厂在工作: public void produceCloth()"); factory.produceCloth(); System.out.println("代理工厂后续工作:public void produceCloth()"); } } //被代理类 class NikeClothFactory implements ClothFactory{ @Override public void produceCloth() { System.out.println("NikeClothFactory 生产衣服"); } } public class FieldTest { public static void main(String[] args) throws Exception { // 被代理类的对象 ClothFactory nikeClothFactory = new NikeClothFactory(); // 代理类的对象 ClothFactory proxyClothFactory = new ProxyClothFactory(nikeClothFactory); proxyClothFactory.produceCloth(); } }
动态的代码:
package java2_proxy; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; interface Human{ String getBelief(); void eat(String food); } class SuperMan implements Human{ @Override public String getBelief() { return "i can fly";} @Override public void eat(String food) { System.out.println("i like" + food); } } //代理类 class ProxyFactory{ public static Object getProxyInstance(Object object){ // object 被代理类的对象 MyInvocationHandler handler = new MyInvocationHandler(); handler.bind(object); return Proxy.newProxyInstance(object.getClass().getClassLoader(),object.getClass().getInterfaces(),handler); } } class HumanUtil{ public void method1(){ System.out.println("=============public void method1()=========="); } public void method2(){ System.out.println("=============public void method2()=========="); } } class MyInvocationHandler implements InvocationHandler{ // 将被代理类要执行的方法 private Object obj; public void bind(Object obj){ this.obj = obj; } @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { HumanUtil humanUtil = new HumanUtil(); humanUtil.method1(); Object returnValue = method.invoke(obj, args); humanUtil.method2(); return returnValue; } } public class ProxyTest { public static void main(String[] args) { SuperMan superMan = new SuperMan(); Human proxyInstance = (Human) ProxyFactory.getProxyInstance(superMan); System.out.println(proxyInstance.getBelief()); proxyInstance.eat("doufu"); System.out.println("----------"); java2_proxy.NikeClothFactory nikeClothFactory = new java2_proxy.NikeClothFactory(); java2_proxy.ClothFactory proxyInstance1 = (java2_proxy.ClothFactory) ProxyFactory.getProxyInstance(nikeClothFactory); proxyInstance1.produceCloth(); } }