Dynamic agent of Java system

Source: Internet
Author: User

Proxy mode

Before you can learn more about dynamic agents, you need to master the proxy mode first. Only by deeply understanding the application of proxy mode, can we fully understand the convenience of Java Dynamic Agent.
In life there are many use of "proxy mode" scenario, such as: The village of Zhang San this year is 30 years old, but not married, can put his mother to worry bad, so he asked the king of the village Tung Tau matchmaker to find a daughter-in-law for his son.
Here, to marry a daughter-in-law is Zhang San, but he can not run directly to the woman's home to bring back the girl directly, need to intermediary King matchmaker Door matchmaking, here the King Matchmaker is an agent.
In addition, when we go to college, we all know that the school room is through a proxy server online, because there is only one external network IP, not allow each LAN machine directly connected to the outside network.
Furthermore, we usually deploy Nginx in the application front-end as a reverse proxy server in order to protect the application from external network attacks.
In short, we will always have to use proxy mode for some purpose, or because of some limitations.

OK, let's show you how to use proxy mode in the Java world through abstraction in a more common example.
As we all know, the iphone has become a very popular mobile phone brand, some years ago even someone to buy an iphone and sell kidney, can think its brand has long been deeply rooted.
The latest sale of Iphonex is also a very hot mess, so Xiao Ming students can not resist the excitement of the mood also want to buy one to use.
But the first is not on the mainland to sell, but Xiao Ming again in the mainland is not easy to go abroad, then how to do? In e-commerce has already swept the day, obviously this problem is too easy to solve.
So Xiao Ming in an e-commerce website through the overseas purchase of the way you can buy the right machine. Here, Xiao Ming buy mobile phone this thing entrusted to the e-commerce platform of a business, Xiao Ming do not directly to buy, but through the merchant this "agent" to buy mobile phones, and finally by mail the way the goods to Xiao Ming.
So, how to use the program to achieve Xiao Ming using overseas purchasing this way to buy mobile phone?
Until then, we need to make it clear that the realization of computer programs is necessarily an abstraction of real life. So, the first step is to abstract a class called "human".

/*** define "person" class* @desc Org.chench.test.java.Person* @date November 30, 2017 * @version1.0.0 */ Public classperson {/*** Name     */    PrivateString name ="";/*** Age     */    Private intAge =0; PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age= age; }}

We see the definition of basic attributes in the "person" class, such as name, age.
At the same time, we need to abstract a "buyer" interface, declaring the purchase of a specified item method, as follows:

/** * 定义"购买者"接口,声明购买指定物品的方法. * @desc org.chench.test.java.Buyer * @date 2017年11月30日 * @version 1.0.0 */publicinterface Buyer {    /**     * 有人想要买iphonex     */    publicvoidbuyIphoneX();}

Obviously, to do so much preparation, the purpose is to buy Iphonex for Xiao Ming, so the "people" class must also implement the "buyer" interface, that is, the final "person" class should be such a child:

/*** define "person" class* @desc Org.chench.test.java.Person* @date November 30, 2017 * @version1.0.0 */ Public classPersonImplementsBuyer {/*** Name     */    PrivateString name ="";/*** Age     */    Private intAge =0; PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; } Public int Getage() {returnAge } Public void Setage(intAge) { This. Age= age; }@Override     Public void Buyiphonex() {System. out.println(GetName() +"would buy Iphonex"); }}

OK, here we should be able to instantiate an object called "Xiao Ming" to buy Iphonex:

/** * @desc org.chench.test.java.BuySomething * @date 2017年11月30日 * @version 1.0.0 */publicclass BuySomething {    publicstaticvoidmain(String[] args) {        newPerson();        person.setName("小明");        person.buyIphoneX();    }}

Run-time output:小明 will buy iPhoneX
But the problem came, because Iphonex has not been listed on the mainland, and xiaoming can not go abroad, he is unable to buy directly Iphonex.
So Xiao Ming find a "buy a little Prince" business, for him to go overseas for mobile phones, and then mailed to Xiaoming.

/*** @desc org.chench.test.java.BuyerProxyPrinceling* @date November 30, 2017 * @version1.0.0 */ Public classBuyerproxyprincelingImplementsBuyer {PrivateString name ="";PrivatePerson Realbuyer =NULL; Public buyerproxyprinceling(String name, person Realbuyer) { This.name= name; This.Realbuyer= Realbuyer; } PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; }@Override     Public void Buyiphonex() {System. out.println(GetName() +"Buy Iphonex"); Realbuyer.Receiveiphonex("Iphonex"); }}

First, "Buy the Little Prince" to buy Iphonex, also need to implement the "buyer" interface.
Secondly, in order to buy a mobile phone after the machine sent to Xiao Ming, in the "people" category also need to define a method of receiving Iphonex, otherwise, the purchase of the handset after the phone can not give xiaoming ah.
In the "People" class, add the following method:

publicvoidreceiveIphoneX(String iPhoneX) {    System.out.println(getName" received " + iPhoneX);}

Ready, overseas purchasing to find good, Xiao Ming need to find "purchasing the little Prince" buy Iphonex ^^^^

/*** @desc org.chench.test.java.BuySomething* @date November 30, 2017 * @version1.0.0 */ Public classbuysomething { Public Static void Main(string[] args) {Person person =New  Person(); Person.SetName("Xiao Ming");//Xiao Ming can't buy phone directly        //Person.buyiphonex ();Buyerproxyprinceling Buyerproxy =New buyerproxyprinceling("The Little Prince of shopping", person);//Xiao Ming through the agent to buy mobile phoneBuyerproxy.Buyiphonex(); }}

Run output:

代购小王子 buy iPhoneX小明 received iPhoneX

Xiao Ming finally through overseas purchasing the way to buy the right mobile phone, this should be good to show off the bar ~
Here, we in the software implementation of Xiao Ming called the target object, purchasing merchants called the proxy object, through the proxy object to complete the target object can not complete the action.

As you can see from this very simple example, in order to implement an operation through a proxy, the business interface must be defined first, and then both the target object class and the Proxy object class must implement the business interface.
At the same time, the proxy object must hold a reference to the target object, making it easier for the proxy object to contact the target object after performing an operation.
Although the goal is achieved, it is cumbersome to achieve. Specific to the programming implementation, need to do too much hard coding, which we have been pursuing a simple and flexible goal is very unfriendly.
In fact, the way to implement this proxy pattern is called static proxy.
Java since the 1.3 version of the proposed dynamic agent support, this dynamic agent can bring what convenience? What are the advantages of dynamic proxies compared to static proxies? What are the advanced operations that can be achieved with dynamic proxies?

Dynamic Agent Dynamic proxy class overview

The official definition of the dynamic proxy class is:

A dynamic proxy class is a class that implements a list of interfaces specified at runtime such that a method invocation through one of the interfaces on an instance of the class will be encoded and dispatched to another object through a uniform interface.

The meaning of translation comes from:

动态代理类是一个实现在运行时指定接口列表的类,使得这些接口实现类的实例中的某个方法调用将被编码并通过统一的接口分派到另一个对象。

This definition is very blunt, but there are a few things that can be drawn from it:
(1) Dynamic proxy classes need to implement some specified interfaces and are specified at run time, that is, dynamic proxy classes do not need to explicitly implement these interfaces at encoding time.
(2) A method call to an instance of a class that implements these interfaces will be encoded and dispatched to another object through a unified interface (which is actually assigned to the proxy object).

Then we need to further determine:
(1) What interfaces does this dynamic proxy class need to specify at run time?
(2) Who will encode the method calls of the implementation class instances of these interfaces? will be coded why?
(3) What interface is the "unified interface" for the method invocation of the implementation class instance that allocates these interfaces? What is the assigned object?
(4) What can I do with this dynamic proxy class?

With these questions, continue to see the official description of the Dynamic proxy class feature:

    • You can use dynamic proxy classes to create type-safe proxy objects for the interface list without having to pre-generate proxy classes, such as using compile-time tools.
    • A method call to an instance of a dynamic proxy class is dispatched to a single method in the invocation handler of the instance, and is encoded as an array of Java.lang.reflect.Method objects that identify the method being called and an object type that contains the method arguments.
    • Dynamic proxy classes are useful for applications or libraries that require a type-safe invocation of an object that needs to render an interface API. For example, an application can use a dynamic proxy class to create an object that implements multiple arbitrary event listener interfaces (extension java.util.eventlistener--) to handle a variety of different types of events in a uniform manner (for example, by logging all such events to a file).

Now that the dynamic proxy class is so forked, how do you create and use it?

Dynamic proxy class Practice

or before xiaoming overseas purchase Iphonex example, write dynamic proxy class.

/*** "Overseas Purchase" Dynamic proxy class* @desc Org.chench.test.java.BuyerDynimicProxy* @date December 1, 2017 */ Public classBuyerdynimicproxyImplementsInvocationhandler {PrivateString name ="Overseas purchasing merchant";PrivateObject Realbuyer =NULL;Private Buyerdynimicproxy(Object obj) { This.Realbuyer= obj; } Public StaticObjectnewinstance(Object obj) {//Returns the object's dynamic proxy object, which is dispatched to the dynamic proxy object's Invoke method when the method of the proxy object is called        returnProxy.newproxyinstance(obj.GetClass().getClassLoader(), obj.GetClass().getinterfaces(),New Buyerdynimicproxy(obj)); }@Override     PublicObjectInvoke(Object Proxy, Method method, object[] args)throwsThrowable {//When Xiao Ming wants to buy a mobile phone, it will trigger the dynamic agent to buy, bought and mailed to XiaomingObject result = method.Invoke(Realbuyer, args); This.Dobuyiphonex();if(Realbuyerinstanceofperson) {Person person = (person) Realbuyer;//Mail the phone to xiaomingPerson.Receiveiphonex("Iphonex"); }returnResult } PublicStringGetName() {returnName } Public void SetName(String name) { This.name= name; }/*** Agent object to buy Iphonex     */    Private void Dobuyiphonex() {System. out.println(GetName() +"Buy Iphonex"); }}

Purchasing mobile phone by Dynamic proxy object:

/** * @desc org.chench.test.java.BuySomething * @date 2017年11月30日 * @version 1.0.0 */publicclass BuySomething {    publicstaticvoidmain(String[] args) {        newPerson();        person.setName("小明");                // 通过动态代理给小明代购手机        Buyer buyerDynimicProxy = (Buyer) BuyerDynimicProxy.newInstance(person);        buyerDynimicProxy.buyIphoneX();    }}

Output Result:

小明 will buy iPhoneX海外代购商家 buy iPhoneX小明 received iPhoneX
Summarize

To buy a mobile phone in a small Ming dynasty we can see that using a dynamic proxy provides more flexibility and decoupling than using a static proxy, mainly in:

动态代理类不需要在编码中明确实现业务接口(BuyerDynimicProxy并未实现Buyer接口),而是在运行时动态指定。这样一个动态代理类就可以很方便地实现同时代理多种业务(比如BuyerDynimicProxy除了可以代购手机,还可以代理购房),而静态代理需要明确实现多个代理接口。

In fact, the so-called dynamic agent is that Java provides a mechanism that allows developers to flexibly and easily implement the application of proxy mode in programming, without the need to implement a large number of repetitive coupling of large hard-coded.
Dynamic proxies are the cornerstone of the Spring AOP framework, because of the advent of Java dynamic proxies, making it possible to program in Java for slicing.
Despite the flexibility, dynamic agents also need to follow certain conventions:
The dynamic proxy class must implement the Java.lang.reflect.InvocationHandler interface for the target object to notify the proxy object when it executes the business interface method.
In addition, dynamic proxies are simply a means of flexible use of proxy patterns provided by Java for application programming, but they are not required and can be achieved with some consideration of static proxies.

Reference
http://blog.csdn.net/carson_ho/article/details/54910472 Proxy pattern-the most understandable design pattern parsing

Dynamic agent of Java system

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.