Design Mode: manually write a proxy Mode
Proxy mode: provides a replacement or placeholder for another object to access this object. The proxy mode provides representatives for another object to control the access to the object. There are many ways to manage access.
The remote agent manages the interaction between the customer and the remote object.
The virtual proxy controls objects with high access instantiation overhead.
The proxy controls access to object methods based on callers.
The proxy mode has many variants, such as cache proxy, synchronization proxy, firewall proxy, and copy proxy during write.
The built-in Proxy Support of Java allows you to dynamically create a proxy as needed and allocate all calls to the selected invocation processor (InvocationHandler ).
The following example is a protection proxy.
Class diagram:
The source code is as follows:
Package javaproxy;/*** proxy interface * @ author Arvon **/public interface PersonBean {public String getName (); public String getGender (); public String getInterests (); public int getHotAndNotRating (); public void setHotAndNotRating (int rating); public void setInterests (String interests); public void setName (String name); public void setGender (String gender );}
package javaproxy;public class PersonBeanImpl implements PersonBean {String name;String gender;String interests;int rating, ratingCount =1;public PersonBeanImpl(String name, String gender, String interests, int rating) {super();this.name = name;this.gender = gender;this.interests = interests;this.rating = rating;}@Overridepublic String toString() {return PersonBeanImpl [name= + name + , gender= + gender + , interests= + interests + , rating= + getHotAndNotRating()+ ];}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public String getInterests() {return interests;}public void setInterests(String interests) {this.interests = interests;}@Overridepublic int getHotAndNotRating() {return ratingCount==0?0:(rating/ratingCount);}public void setHotAndNotRating(int rating){this.rating+=rating;ratingCount++;}}
Package javaproxy; import java. lang. reflect. invocationHandler; import java. lang. reflect. method;/*** InvocationHandler is responsible for processing the requests sent by the proxy class (that is, the call of the proxy class) * @ author Administrator **/public class OwnerInvocationHandler implements InvocationHandler {PersonBean person; public OwnerInvocationHandler (PersonBean person) {super (); this. person = person;}/*** Parameters: proxy-the proxy instance that the method was invoke D * onmethod-the Method instance corresponding to the interface method * invoked on the proxy instance. the declaring class of the Method object * will be the interface that the method was declared in, which may be a * superinterface of the proxy interface that the proxy class inherits the * method through. args-an array of objects ining the values of the * arguments passed in the method I Nvocation on the proxy instance, or null * if interface method takes no arguments. arguments of primitive types are * wrapped in instances of the appropriate primitive wrapper class, such as * java. lang. integer or java. lang. boolean. returns: the value to return from * the method invocation on the proxy instance. if the declared return type * of the interface method is a primitive type, then the valu E returned by * this method must be an instance of the corresponding primitive wrapper * class; otherwise, it must be a type assignable to the declared return * type. if the value returned by this method is null and the interface * method's return type is primitive, then a NullPointerException will be * thrown by the method invocation on the proxy instance. if the value * returned by this method I S otherwise not compatible with the interface * method's declared return type as described above, a ClassCastException * will be thrown by the method invocation on the proxy instance. * // @ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws IllegalAccessException {try {if (method. getName (). startsWith (get) return method. invoke (person, args); // method executor person else if (method. g EtName (). equals (setHotAndNotRating) throw new IllegalAccessException (); else if (method. getName (). startsWith (set) return method. invoke (person, args); // method executor person} catch (Exception e) {// e. printStackTrace (); System. out. println (cannot set rating by owner proxy !);} Return null; // will not be processed if other methods are called }}
Package javaproxy; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; public class NonOwnerInvocationHandler implements InvocationHandler {PersonBean person; public NonOwnerInvocationHandler (PersonBean person) {super (); this. person = person ;}@ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws Throwable {try {if (method. getName (). startsWith (get) return method. invoke (person, args); // method executor person else if (method. getName (). equals (setHotAndNotRating) return method. invoke (person, args); else if (method. getName (). startsWith (set) // others' information cannot be set. throw new IllegalAccessException ();} catch (Exception e) {System. out. println (cannot set infos from nonowner proxy ...);} return null; // will not be processed if other methods are called }}
Package javaproxy; import java. lang. reflect. proxy; /*** dynamically generate the proxy class * @ author Administrator **/public class ProxyHelper {/*** Returns an instance of a proxy class for the specified interfaces that * dispatches method invocations to specified invocation handler. * @ param person * @ return */public static PersonBean getOwnerProxy (PersonBean person) {return (PersonBean) Proxy. newProxyInstance (person. getClass (). getClassLoader (), person. getClass (). getInterfaces (), new OwnerInvocationHandler (person);} public static PersonBean getNonOwnerProxy (PersonBean person) {return (PersonBean) Proxy. newProxyInstance (person. getClass (). getClassLoader (), person. getClass (). getInterfaces (), new NonOwnerInvocationHandler (person ));}}
Package javaproxy;/*** test class ** @ author Administrator **/public class ProxyTest {public static void main (String [] args) {PersonBean person = new PersonBeanImpl (Jay, F, java, 7); System. out. println (person); // dynamically generate the proxy class ownerProxy (the proxy class ownerProxy implements the PersonBean Interface) PersonBean ownerProxy = ProxyHelper. getOwnerProxy (person); System. out. println (Name is + ownerProxy. getName ()); // proxy method setInterests called proxy ownerProxy will forward this call to OwnerInvocationHandler // when ownerProxy is instantiated, the specified invocation processor is OwnerInvocationHandler // then OwnerInvocationHandler calls its own invoke Method // OwnerInvocationHandler may forward it to the proxy PersonBean person for processing, such as return method. invoke (person, args); // method executor person // other processing may also be done, such as throwing an exception ownerProxy. setInterests (python); System. out. println (person); try {ownerProxy. setHotAndNotRating (8);} catch (Exception e) {} PersonBean nonOwnerProxy = ProxyHelper. getNonOwnerProxy (person); System. out. println (Name is + nonOwnerProxy. getName (); try {nonOwnerProxy. setHotAndNotRating (9); nonOwnerProxy. setInterests (python);} catch (Exception e) {} System. out. println (person );}}
Program output:
PersonBeanImpl [name = Jay, gender = F, interests = Java, rating = 7]
Name is Jay
PersonBeanImpl [name = Jay, gender = F, interests = python, rating = 7]
Cannot set rating by owner proxy!
Name is Jay
Cannot set infos from nonowner proxy...
PersonBeanImpl [name = Jay, gender = F, interests = python, rating = 8]