本文主要是介绍Design Pattern—— Dynamic Proxy Pattern(三) 动态代理模式,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
done by myself
通过下面例子,进一步演示 动态代理 的强大特性,将会体会到 相对于静态static代理,动态可实现 一个proxy代理不同的真实对象。灵活多变。只需要在Client类 调整要代理的角色,无需改动其他部分。使代理角色、真实角色的对应关系更松散了。
抽象角色:
package com.proxy.severalCase;public interface AbstractRole {void print();void sayHello();
}
两个真实角色:
package com.proxy.severalCase;public class RealRole1 implements AbstractRole{@Overridepublic void print() {System.out.println("Printed By RealRole One.");}@Overridepublic void sayHello() {System.out.println("Hello from RealRole One.");}
}
package com.proxy.severalCase;public class RealRole2 implements AbstractRole{@Overridepublic void print() {System.out.println("Printed By RealRole Two.");}@Overridepublic void sayHello() {System.out.println("Hello from RealRole Two.");}
}
实现InvocationHandler的类:
package com.proxy.severalCase;import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;public class InvocationClass implements InvocationHandler {private Object proxyRole;public InvocationClass(Object o) {this.proxyRole = o;}public InvocationClass() {}public void setProxyRole(Object o) {this.proxyRole = o;}@Overridepublic Object invoke(Object proxy, Method method, Object[] args)throws Throwable {return method.invoke(proxyRole, args);}}
Client类:
package com.proxy.severalCase;import java.lang.reflect.Proxy;public class Client {public static void main(String[] args) {AbstractRole proxyRole = null; //同一个代理proxy 代理不同的真实对象InvocationClass handler = new InvocationClass();handler.setProxyRole(new RealRole1());proxyRole = (AbstractRole) Proxy.newProxyInstance(InvocationClass.class.getClassLoader(),new Class[] { AbstractRole.class }, handler);proxyRole.print();proxyRole.sayHello();System.out.println("-------------------------------");handler.setProxyRole(new RealRole2());proxyRole = (AbstractRole) Proxy.newProxyInstance(handler.getClass().getClassLoader(), proxyRole.getClass().getInterfaces(),handler);proxyRole.print();proxyRole.sayHello();}
}
输出结果:
这篇关于Design Pattern—— Dynamic Proxy Pattern(三) 动态代理模式的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!