Proxy mode and JDK dynamic proxy

Source: Internet
Author: User

Proxy mode and JDK dynamic proxy

1. Proxy Mode

In the proxy mode, the active part is the proxy, and the actual officer is the proxy object, that is, the active part is not the same as the active part.

Here we will take the classic Railway Station and train ticket sales representative as an example.

 

package testproxy;public interface SellTicket {public void sellTicket();}
The SellTicket interface has only one way to sell tickets. All classes that implement this interface have the capability to sell tickets. First, the railway station has the ability to sell tickets:

 

 

Package testproxy; public class RailwayStation implements SellTicket {@ Overridepublic void sellTicket () {System. out. println (train station ticket );}}
Then, the train ticket agent can sell tickets:

 

 

Package testproxy; public class RailwayStationProxy implements SellTicket {SellTicket sellTicket; public RailwayStationProxy () {this. sellTicket = new RailwayStation () ;}@ Overridepublic void sellTicket () {System. out. println (start ticket sales); this. sellTicket. sellTicket (); System. out. println (ticket sold successfully );}}
Unlike the railway station, the railway station does not have a ticket on behalf of the sales site. It can be seen that the agent sales site is only a live service, that is, an agent. The railway station is the real target, that is, the target of the agent.

 

Here is a customer who buys tickets:

 

package testproxy;public class Client {public static void main(String[] args) {SellTicket sellTicket = new RailwayStationProxy();sellTicket.sellTicket();}}
The process of buying a ticket is as follows:

 

Start ticket sales
Railway Station ticket sales
Ticket sold successfully

It can be seen that the agent participates in the ticket sales activity, but the real ticketing is the railway station.

To sum up, the proxy mode: both the proxy and the objects to be proxies claim that they have the ability to do something for the client to call, so they must inherit the same interface; however, the agent does not really have the ability to do something, so he needs to have a reference to the agent object. When the customer asks the agent, it will let the agent do it.

2. JDK dynamic proxy

JDK dynamic proxy allows us to create a proxy object without creating a proxy class.

The Proxy object is created through the static method of the java. lang. reflect. Proxy class:

NewProxyInstance (ClassLoader loader, Class [] Interfaces, InvocationHandler h)

Its parameters are the Class loader, the Class array that declares the capabilities of the proxy, and a call processor. The class loader is used to load the interface, and the call processor is used to associate the proxy object with the proxy object. The following method is used to call the processor:

Invoke (Object proxy, Method method, Object [] args)

Proxy is a proxy object. method is the Method object corresponding to the method of the proxy object called by the client. args is the parameter that the client sends to the calling Method. Each time the client calls a method on the proxy object, the invoke method that calls the processor is called.

Here we also use the example of Railway Station and train ticket sales representative:

There is also an interface for declaring the capabilities of proxy objects and objects to be proxies:

 

package testproxy;public interface SellTicket {public void sellTicket();}

Then there is a train station with ticket sales capabilities:

 

 

Package testproxy; public class RailwayStation implements SellTicket {@ Overridepublic void sellTicket () {System. out. println (train station ticket );}}

To implement dynamic proxy, we also need a call processor:

 

 

Package testproxy; import java. lang. reflect. invocationHandler; import java. lang. reflect. method; public class SellTicketHandler implements InvocationHandler {private Object target; public SellTicketHandler (Object target) implements get = target ;}@ Overridepublic Object invoke (Object proxy, Method method, Object [] args) throws Throwable {System. out. println (start ticket sales); method. invoke (target); System. out. println (ticket sold successfully); return null ;}}

Call the invoke method of the processor to call the corresponding method on the proxy object.

 

Next, create a proxy object on the client and call the above method:

 

package testproxy;import java.lang.reflect.InvocationHandler;import java.lang.reflect.InvocationTargetException;import java.lang.reflect.Method;import java.lang.reflect.Proxy;public class DynamicProxy {public static void main(String[] args) {RailwayStation railwayStation = new RailwayStation();InvocationHandler handler = new SellTicketHandler(railwayStation);Class[] interfaces = new Class[] {SellTicket.class};Object proxy = Proxy.newProxyInstance(handler.getClass().getClassLoader(), interfaces, handler);try {Method method = SellTicket.class.getMethod(sellTicket);method.invoke(proxy);} catch (NoSuchMethodException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (SecurityException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalAccessException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (InvocationTargetException e) {// TODO Auto-generated catch blocke.printStackTrace();}}}

Running result:

 

Start ticket sales
Railway Station ticket sales
Ticket sold successfully

 

Final Conclusion: Both the proxy mode and the JDK dynamic proxy have the following elements: proxy, the proxy object, and interfaces that claim their capabilities; only the dynamic proxy does not need to be shown to create a proxy class.

 

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.