"Java Technology drip"--proxy mode and its application to transaction encapsulation

Source: Internet
Author: User

background

In the project we will encounter a situation in which the same code is added to several methods that are not business-agnostic, and that we may need to change them one at a time due to ill-conceived or changing requirements or other reasons. For example, such as log control in a program, transaction control, etc., these functions are not business-independent, but they need to be mixed with our logic to achieve some special requirements.

In this case, the code is often the same, can be drawn out, in order to reuse, we can put these same code in a separate way for the other needs of the call, so that in the future to modify the effect of only one place, to achieve the reuse of the program, but another problem is that Someday we may not need such a feature, we need to remove the code that invokes these functions one by another, and when the parameter or return value of the method changes, it may be necessary to make changes to each call.

Based on the above problems, we can use the proxy mode to solve.


Basic Introduction

Proxy Mode ( P Roxy ): Provides a proxy for other objects to control access to this object.

To put it bluntly, we add a layer (the proxy class) between the target object that needs to be called, and we don't call the previous target object directly, but indirectly through the proxy class, so that we can do the extraction function in the proxy.


Proxy mode class diagram schematic

The previous direct invocation method

Extracting public invocation parts using proxy mode


category

Static:

The proxy class in the static proxy is visible and can be seen, and at compile time, the method to be executed is determined. There are too many proxy classes in the static proxy. For a more flexible implementation, we can use dynamic proxies.


Dynamic: proxy class Runtime determination

Use:

1. The target class must implement an interface

2. Setting up a control class for proxy objects

Implementing Invocationhandler, encapsulating the method of generating proxy classes based on the target object, the caller first invokes the Newproxyinstance method of the proxy (this section can be encapsulated by applying Factory mode, can be removed later or changed proxy class), generated and converted to the proxy class , calling the target method of this class, you can callback to the Invocationhandler implementation class's Invoke method


Example-Dynamic agent encapsulation transaction

public class Transactionhandler implements Invocationhandler {Private Object Targetobject;public object Newproxyinstance (Object targetObject) {this.targetobject = Targetobject;return proxy.newproxyinstance ( Targetobject.getclass (). getClassLoader (), <span style= "font-family:kaiti_gb2312;" > </span>targetobject.getclass (). Getinterfaces (), this);} public object invoke (object proxy, Method method, object[] args) throws Throwable{connection conn = Null;object ret = null    ; try{conn = Connectionmanager.getconnection ();//The configuration of the open transaction can take the configuration file, which can be more flexible if (method.getname (). StartsWith ("save") | |   Method.getname (). StartsWith ("remove") | | Method.getname (). StartsWith ("Modify")) {//manual control Transaction commit connectionmanager.begintransaction (conn);} Call the business logic method of the target object ret = Method.invoke (targetObject, args);//judgment, when Autocommit is set to false, the control commits if (!conn.getautocommit ()) { Commit TRANSACTION CONNECTIONMANAGER.COMMIT (conn);}} catch (Exception e) {e.printstacktrace ();//dynamic agent encapsulates our custom exception if (e instanceof invocationtargetexception) {InvocaTiontargetexception ete = (invocationtargetexception) e;throw ete.gettargetexception ();} ROLLBACK TRANSACTION connectionmanager.rollbacktransaction (conn); throw new ApplicationException ("Operation failed! ");} Finally{connectionmanager.closeconnection ();} return ret;}}

Note: The class Connectionmanage implementation in this example is described in "Java Technology drip"--threadlocal encapsulating JDBC Transaction operations

In this kind of encapsulation, we can implement the service layer in the need for transaction operations in the place without writing the transaction-related code every time, as long as the service layer class generation agent, callback this class of Invoke method can achieve transaction control, This allows for good reuse and higher maintainability.


Summarize

Just because proxy mode brings us a filter-like interception mechanism that allows us to do something before invoking the target method, doing something after invoking the target method, so that we can achieve the effect that our general programming theory cannot achieve, plus some additional applications that are flexible to configure, The application of proxy mode can be said to be quite extensive, and it also provides more ideas and ideas for future program design.

"Java Technology drip"--proxy mode and its application to transaction encapsulation

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.