DRP Summary-Understanding the proxy model in practice

Source: Internet
Author: User

Preface


When JDBC accesses a database, the method of adding and removing changes is to do the manual transaction, so when each method executes, it writes the transaction code. When the code is not comfortable, we have to think about the object-oriented thinking, so many times to repeat the same code is wrong, so we need to abstract and encapsulation, so there is a design pattern.


Proxy Mode


Proxy mode: Provides a proxy for other objects to control access to this object. To give an example of life, if we buy something, we do not go to the factory to buy directly, but to shop to buy, then the mall is the factory's proxy class. In the single responsibility principle of the class, a class should do only one thing, so the factory class should not do the sales work, the mall class also do not do the work of production.



As you can see, there are three types of roles in the proxy mode:


Subject: Abstract topic interface, an interface that is implemented by both the proxy role and the real role, indicates that proxy roles can be used wherever real roles are used.


Realsubject: Real role, the real object represented by the agent role, all the things that the agent does is actually the real role.


Proxy: Agent role, in place of the real role and the use of the real role of the object to deal with, of course, its work only "negotiation", as for the specific implementation or rely on the real role.


The proxy mode has many applicable places, one of the common remote Agent proxy modes, and it can also be used to load large resources or create longer objects.


Static proxy


The static proxy class is actually a proxy class that is written by the programmer and already exists before the program runs. Just let the proxy class and the delegate class implement an interface at the same time, the proxy class can work for the delegate class.


Agent Interface (Subject):


Public interface Usermanager {public void AddUser (string userId, string userName);


Real Character (Realsubject):


public class Usermanagerimpl implements Usermanager {public void AddUser (string userId, String userName) {try {System.out]. println ("Usermanagerimpl.adduser () userid-->>" + userId);} catch (Exception e) {e.printstacktrace (); throw new RuntimeException ();}}}


Agent Role (proxy):


public class Usermanagerimplproxy implements Usermanager {private Usermanager usermanager;public usermanagerimplproxy ( Usermanager usermanager) {this.usermanager = Usermanager;} public void AddUser (string userId, String userName) {try {System.out.println ("Start-->>adduser () userid--> > "+ userid"; Usermanager.adduser (userid, userName); System.out.println ("Success-->>adduser ()");} catch (Exception e) {e.printstacktrace (); System.out.println ("Error-->>adduser ()");}}}


Client:


public class Client {public static void main (string[] args) {Usermanager Usermanager = new Usermanagerimplproxy (New Userma Nagerimpl ()); Usermanager.adduser ("0001", "Zhang San");}}


such a static proxy mode is completed, in fact, from the above code can be seen, this proxy class is the Agent Realsubject processing a similar log things, but if the delegate class needs to do other things proxy class, then you have to re-create a new proxy class, which is the disadvantage of static agents, Agent things more, need to write a lot of proxy class, not easy to maintain. At this time, we can use the dynamic proxy approach.


Dynamic Agent


In Java, there is a Invocationhandler interface, which takes the mechanism of dynamic proxy, the proxy class implements the Newproxyinstance (object TargetObject) method in this interface and the Invoke (object Proxy, method, object[] args), you can implement the instantiation of the proxy class and the execution of the agent event separately. The code of the proxy interface, the client and the delegate class is unchanged, but the code for the proxy class changes, as opposed to the static proxy.


Agent Class (proxy):


public class Loghandler implements Invocationhandler {Private Object targetobject;//creates an instance of a proxy class, passing in an object, no matter what object public objects Newproxyinstance (Object targetObject) {this.targetobject = Targetobject;return proxy.newproxyinstance ( Targetobject.getclass (). getClassLoader (),   Targetobject.getclass (). Getinterfaces (), this);} Invoking the proxy method, passing in an instance of the proxy class, after doing what the proxy class should do, will recall the method of the delegate class public object invoke (object proxy, Method method, object[] args) throws Throwable {System.out.println ("start-->>" + method.getname ()); for (int i=0; i<args.length; i++) { System.out.println (Args[i]);} Object ret = null;try {//Call target method ret = Method.invoke (targetObject, args); System.out.println ("success-->>" + method.getname ()); }catch (Exception e) {e.printstacktrace (); System.out.println ("error-->>" + method.getname ()); throw e;} return ret;}}


Client code:


public class Client {public static void main (string[] args) {Loghandler Loghandler = new Loghandler (); Usermanager Usermanager = (usermanager) loghandler.newproxyinstance (New Usermanagerimpl ()); UserManager.addUser (" 0001 "," Zhang San "); Usermanager.deluser (" 0001 ");}}
the advantage of dynamic proxies over static proxies is that proxy classes are created only when they are needed, rather than coming up with no need to create them.


Dynamic Agent Encapsulation Transactions


In the DRP, the dynamic proxy is used in the encapsulation transaction, each method that accesses the database executes the method of the dynamic proxy class, if adding or removing the method, it opens, commits the transaction, rolls back the transaction if there is an exception, and if it is the method of the query, the transaction is not executed. In fact, the best query also put in the transaction inside, but here did not do.


public class Transactionhandler implements Invocationhandler {Private Object Targetobject;public object Newproxyinstance (Object targetObject) {this.targetobject = Targetobject;return proxy.newproxyinstance ( Targetobject.getclass (). getClassLoader (), Targetobject.getclass (). Getinterfaces (), this);} public object invoke (object proxy, Method method, object[] args) throws Throwable {Connection conn = null;object ret = null try {//Get Connectionconn = Connectionmanager.getconnection () from Threadlocal, if (Method.getname (). StartsWith ("add") | | Method.getname (). StartsWith ("del") | | 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); if (!conn.getautocommit ()) {// Commit TRANSACTION connectionmanager.committransaction (conn);}} catch (ApplicationException e) {//ROLLBACK TRANSACTION connectionmanager.rollbacktransaction (conn); throw e;} catch (Exception e) {e.printstacktrace (); 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;}}


Summary


Whether it is a dynamic agent or a static proxy, will always establish a variety of proxy classes for the delegate class, the class is more natural and not easy to manage, which is one of the shortcomings of the proxy mode. The difference between dynamic agent and static proxy is that when the proxy class is created differently during the execution, the static proxy is to write the class well before the program runs, and dynamic agent is created dynamically during the execution. Here the execution of the dynamic agent, very much like the aspect-oriented programming, it in the program execution, horizontal cut in to check, if it is added and removed to change the method, then perform manual transaction processing.

DRP Summary-Understanding the proxy model in practice

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.