Java proxy Mode

Source: Internet
Author: User

Proxy mode is one of the commonly used design modes. The new idea is to insert a proxy object between the actual object and the caller to provide additional processing or different operations. These additional operations usually need to communicate with the actual object. The proxy mode generally involves the following roles:

Abstract role: Declares the common interfaces of real objects and proxy objects;

Proxy role: the proxy object role contains a reference to the real object to operate on the real object. At the same time, the proxy object provides the same interface as the real object to replace the real object at any time. At the same time, the proxy object can append other operations when performing real object operations, which is equivalent to encapsulating real objects.

Real role: the real object represented by the proxy role is the object we finally want to reference.

 

The following uses sending a message as an example to illustrate the basic implementation of a simple proxy mode:

First, define the purpose: to send a message, define the corresponding interface MessageHandler according to the purpose. Additional operation required: assume that the length of the message to be verified cannot exceed the specified length and cannot be blank. In addition, we need to count the number of sent messages. If the length exceeds the specified number, we need to output an alarm. We use the proxy mode to implement this additional operation. The following shows the corresponding class relationship diagram and sample code.

 

// Interface Definition
Public interface MessageHandler {
Public void sendMessage (String msg );
}

// Implementation class for sending messages by Email
Public class EmailMessage implements MessageHandler {
@ Override
Public void sendMessage (String msg ){
// TODO Auto-generated method stub
System. out. println (msg + "send !! ");
}
}

// Message Processing proxy
Public class MessageProxy implements MessageHandler {
Private static int count;
Private MessageHandler emailMsg;

@ Override
Public void sendMessage (String msg ){
// TODO Auto-generated method stub
If (checkMessage (msg )){
If (emailMsg = null)
EmailMsg = new EmailMessage ();
Count ++;
EmailMsg. sendMessage (msg );
System. out. println ("Message sent:" + count );
}
}

Private boolean checkMessage (String msg ){
Return msg! = Null & msg. length ()> 10;
}
}

// Call class
Public class MainClass {
Private static void runProxy (MessageHandler handler ){
Handler. sendMessage ("message for test ");
}

/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
RunProxy (new EmailMessage ());
System. out. println ("++ ");
RunProxy (new MessageProxy ());
}
}

Output
Message for test send !!
+++ ++ Pjroxy ++
Message for test send !!
Message sent: 1


In this example, we can easily add various additional processing methods in the message sending process, and also conveniently Replace the message processing methods, if you replace the message sent by Email with the message sent by SMS, the caller will not notice it! When you want to separate some additional operations from specific objects, especially when you want to easily make modifications or insert some additional operations before the method of a specific object is executed, proxy is very useful!

 

Dynamic proxy

The introduction of the dynamic proxy mechanism in java makes the idea of the proxy mode more perfect and progressive. It allows the dynamic creation of proxy and supports dynamic calls to the proxy method. The Java Dynamic proxy class is located under the Java. lang. reflect package and generally involves the following two classes:

(1). Interface InvocationHandler: this Interface defines only one Method Object: invoke (Object obj, method Method, Object [] args ). In actual use, the first parameter obj generally refers to the proxy class, and the method is the method to be proxy. In the preceding example, request () and args are the parameter arrays of this method. This abstract method is dynamically implemented in the proxy class.

(2). Proxy: this class is a dynamic Proxy class, which is similar to ProxySubject in the previous example. It mainly includes the following content:

Protected Proxy (InvocationHandler h): constructor, which is used to assign values to the internal h.

Static Class getProxyClass (ClassLoader loader, Class [] interfaces): obtains a proxy Class. loader is the Class loader, and interfaces is the array of all interfaces of the real Class.

Static Object newProxyInstance (ClassLoader loader, Class [] interfaces, InvocationHandler h): returns an instance of the proxy Class, the returned proxy class can be used as a proxy class (the method declared in the Subject interface of the proxy class can be used ).

 

Dynamic Proxy is such a class: it is a class generated at runtime. You must provide a set of interfaces to it when generating it, then the class declares that it implements these interfaces. Of course, you can use the class instance as any of these interfaces. Of course, this Dynamic Proxy is actually a Proxy, and it will not do substantial work for you. When generating its instance, you must provide a handler to take over the actual work. Next we will use a dynamic proxy to re-implement the above message sending example!

 

 

Based on the above example, we first add a processing class for sending messages via SMS:

Public class SmsMessage implements MessageHandler {
@ Override
Public void sendMessage (String msg ){
// TODO Auto-generated method stub
System. out. println ("SMS Message:" + msg + "sent! ");
}
}
// Dynamic proxy
Import java. lang. reflect. InvocationHandler;
Import java. lang. reflect. Method;
Public class DynamicMessageProxy implements InvocationHandler {
Private static int count;
Private MessageHandler msgHandler;
Public DynamicMessageProxy (MessageHandler handler ){
MsgHandler = handler;
}
@ Override
Public Object invoke (Object proxy, Method method, Object [] args)
Throws Throwable {
// TODO Auto-generated method stub
System. out. println ("++ ====================+++ ");
System. out. println ("proxy:" + proxy. getClass ());
System. out. println ("method:" + method );
System. out. println ("++ ====================+++ ");
If (args! = Null & args. length = 1 & checkMessage (String) args [0]) {
Count ++;
System. out. println ("Message sent:" + count );
Return method. invoke (msgHandler, args );
}
Return null;
}
Private boolean checkMessage (String msg ){
Return msg! = Null & msg. length ()> 10;
}
}
// The following is the call
Import java. lang. reflect. Proxy;
Public class MainClass {
Private static void runProxy (MessageHandler handler ){
Handler. sendMessage ("message for test ");
}
/**
* @ Param args
*/
Public static void main (String [] args ){
// TODO Auto-generated method stub
// RunProxy (new EmailMessage ());
// System. out. println ("++ Proxy ++ ");
// RunProxy (new MessageProxy ());
MessageHandler handler = new EmailMessage ();
RunProxy (handler );
MessageHandler proxy = (MessageHandler) Proxy. newProxyInstance (
MessageHandler. class. getClassLoader (),
New Class [] {MessageHandler. class}, new DynamicMessageProxy (
Handler ));
RunProxy (proxy );
System. out. println ("++ ");
// Text message method
Handler = new smessage ();
RunProxy (handler );
Proxy = (MessageHandler) Proxy. newProxyInstance (MessageHandler. class
. GetClassLoader (), new Class [] {MessageHandler. class },
New DynamicMessageProxy (handler ));
RunProxy (proxy );
}
}
The output of the above method is as follows:
Message for test send !!
+++ ++ ==========================+++
Proxy: class $ Proxy0
Method: public abstract void MessageHandler. sendMessage (java. lang. String)
+++ ++ ==========================+++
Message sent: 1
Message for test send !!
++
SMS Message: message for test sent!
+++ ++ ==========================+++
Proxy: class $ Proxy0
Method: public abstract void MessageHandler. sendMessage (java. lang. String)
+++ ++ ==========================+++
Message sent: 2
SMS Message: message for test sent!


In the preceding example, a dynamic Proxy object is created by calling the Proxy. newProxyInstance method. This method requires passing in a class loader, a list of interfaces to be implemented by the Proxy, and a specific implementation of the InvocationHandler interface. The dynamic proxy can redirect all calls to the calling processor. Generally, we will pass a time object reference to the processor. The proxy object is passed in the invoke () method. This is very useful when you need to distinguish the request source. For example, you can block the execution of some methods by judging the passed method name! The dynamic proxy mechanism is not frequently used. It is usually used to solve some specific problems, so do not blindly use it for use, depends on your actual needs!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.