Java Agent Detailed

Source: Internet
Author: User

1. Agent Concept

Acting as the name implies, instead of others. There is a proxy pattern in design mode, which defines: Provides a proxy for other objects to control access to such objects.

The proxy class in proxy mode is doing things in lieu of the delegate class. What the proxy class needs to do is preprocess the delegate class, filter the message, forward the message to the delegate class, and process the message afterwards. Agent mode A big feature: for programmers to see To do things proxy class, rather than the original delegate class.

2. Two ways to implement a proxy
2.1 Using Inheritance implementations

Inheritance refers to a class (called a subclass, sub-interface) that inherits another class (called the parent class, the parent interface). in proxy mode, the delegate class acts as a parent class, and the proxy class acts as a subclass. In a proxy class, you can override the method that needs to be proxied in the parent class. the UML diagram and code are as follows.

Package Cn.proxy;public interface Dao {void Add ();}

Package cn.proxy;/** *   class Name: Service   * Class Description: Delegate class * Modified by: Pangfan    * */public class Service implements Dao{public Vo ID Add () {System.out.println ("Add Data to Database!");}}

Package cn.proxy;/** *   class Name: Service1   * Class Description: proxy class---Add a transaction to the delegate class * Modified by: Pangfan    * */public class Service1 extends S ervice{public void Add () {/** * uses inheritance to implement proxy transaction */system.out.println ("Inherit-start Transaction"); Super.add (); System.out.println ("Inheritance--end Transaction");}}

Client Calls

Package Cn.proxy;public class Client {public static void main (string[] args) {//test inheritance implementation of Proxy service t = new Service1 (); T.add ( );}}

2.2 Using combination implementations

The combination is also a special case of the association relationship, which embodies the relationship between the whole and the part, but the whole and part are not divided at this time. in proxy mode, the delegate class acts as a part, and the proxy class as a whole. Delegate classes exist as part of the proxy class, and they are inseparable. in code, the representation of a delegate class as a proxy class in a German member variable exists. the UML diagram and code are as follows.


Package cn.proxy;//Transaction Agent public class Tranproxy implements Dao{private DAO d;//Add Construction method public Tranproxy (Dao D) {super (); . D = D;} public void Add () {System.out.println ("combination-start Transaction");d. Add (); SYSTEM.OUT.PRINTLN ("Combination--end transaction");}}
Package Cn.proxy;public class Client {/** * @param args */public static void main (string[] args) {//test inheritance implemented proxy//service t = New Service1 ();//t.add ();//the agent service s = new service ();D ao d = new Tranproxy (s) of the test combination implementation;d. Add ();


Both inheritance and composition can implement proxy mode, but we usually use the combination method. There are many reasons for this, and I'm here to summarize only two reasons

1. There is a sentence called "can use combination, do not inherit". The degree of coupling of inheritance is very high, which is detrimental to the extension and modification of our code.
2. Use combination to make the code more flexible

For example, in the above program only the agent of the transaction, now needs to change, need to increase the log agent, and require the transaction and log can arbitrarily change the order of execution. Implemented using inheritance and composition, respectively.


Inheritance implementation

Package cn.proxy;//using inheritance to implement proxies---many things public class Service2 extends service{public void Add () {/** * Use inheritance to implement many things: Log transactions and Logs */ System.out.println ("Inheritance-start Transaction"); Super.add (); System.out.println ("Inheritance-end transaction"); System.out.println ("Inheritance--Log");}}

Client Calls

Package Cn.proxy;public class Client {public static void main (string[] args) {//test inheritance implementation of proxy//service t = new Service1 ();//t. Add ();///test combination implementation Agent//service s = new Service ();//dao d = new Tranproxy (s);//d.add ();// Test inheritance to implement a variety of agents--two different order calls two different class service S1 = new Service1 (); S1.add (); Service s2 = new Service2 (); S2.add ();}}

Combination implementation

Package cn.proxy;//Log Agent public class Logproxy implements Dao{private DAO d;public logproxy (dao m) {super (); this.d = D;} public void Add () {System.out.println ("combination-log");d. Add ();}}

Client Calls

Package Cn.proxy;public class Client {public static void main (string[] args) {//test inheritance implementation of proxy//service t = new Service1 ();//t. Add ();///test combination implementation of Agent//service s = new Service ();//dao d = new Tranproxy (s);//d.add ();//test inheritance implements a variety of things--two different sequences need to call two different classes// Service S1 = new Service1 ();//s1.add ();//service s2 = new Service2 ();//s2.add ();// Testing aggregations to implement a variety of things--two different order only need to change the passed parameters of service TT = new service ();//second Tranproxy TP1 = new Tranproxy (TT); Logproxy LP1 = new Logproxy (TP1);D ao dao1 = Lp1;dao1.add ();//second order logproxy LP2 = new Logproxy (TT); Tranproxy TP2 = new Tranproxy (LP2);D ao dao2 = Tp2;dao2.add ();}}

It can be seen from the above that the two implementations are different, and the way to inherit is to add a new proxy class for two different orders, but the combination is not necessary, and so on, if there are new changes in the order of the transaction agent and the log agent. Then the agent of the succession mode needs to increase the class continuously;

and the combination of the way as long as the new agent can not increase the class, the number of classes will not change. inheritance is a high degree of coupling between classes, not conducive to the flexibility between classes, so we can actually use the combination of absolutely no inheritance, such as our decorator pattern and the combination of patterns, they are used by the combination to achieve. However, we can also see from the above example, when the new agent, whether it is inherited or combination of the new proxy classes need to be added, this situation is prone to a class explosion, so the agent can be further improved, the following dynamic agent can solve the problem.

3. Static agents and dynamic agents

The agent is divided into static agent and dynamic agent two kinds.

Static Proxy: The process of creating a proxy class is not hidden. Created by a programmer or a specific tool to automatically generate source code on which to compile. The . class file for the proxy class already exists before the program runs.

Dynamic Proxy: Hides the process of creating a proxy class. Dynamically created using the reflection mechanism while the program is running

so the difference between the two is that before the program runs, . Class whether the file already exists.

The agents we implement with inheritance and composition above are static proxies. For static agents, each of our proxy classes can only serve one interface, so that the sub-program development will inevitably generate an excessive number of agents, and all the agent operation in addition to the method of the use of the same, other operations are the same, then it must be duplicated code. The best way to solve this problem is to complete the proxy function through a proxy class, which must be done using dynamic proxy.

for dynamic agents JDK and the CGLIB Have been implemented, it is convenient for us to use their encapsulated dynamic agents in the development process.

4. Summary

The combination makes the agent flexible, and dynamic proxy enables a proxy class to complete the proxy function. Dynamic proxies make our systems more scalable and flexible. But we also have to look at dynamic agents objectively.

First, the dynamic proxy uses the reflection mechanism, and the reflection is certainly slower than the direct call.

second, reflecting a large number of generated class files can cause Full GC (garbage collection-gabage Collection) cause performance impact. Dynamic proxies do not actually reduce the number of real classes, but hide the process of creating classes. So if a lot of dynamic proxies are used in a system, the generated class files are loaded and stored in the JVM runtime time zone, which causes the full GC when the method area fills up .


Java Agent Detailed

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.