Java Agent mode (proxy mode)

Source: Internet
Author: User

Understand and use design patterns, can cultivate our good object-oriented programming habits, at the same time in practical applications, can be a duck to the ground, enjoy the fun.

Proxy is a more useful model, and more varieties, applications covering the small structure to the whole system of large structure, proxy is the meaning of the agent, we may have a proxy server concept, Agent concept can be interpreted as: between the starting point to the destination has a middle layer, meaning agent.

Definition in design mode: Provides a proxy for other objects to control access to this object.

Why to use proxy mode
    • Authorization mechanism different levels of users have different access rights to the same object, such as the Jive Forum system, the use of proxy for authorization mechanism control, access to the forum there are two kinds of people: Registered users and visitors (unregistered users), In Jive, a proxy such as Forumproxy is in control of both users ' access to the forum.
    • A client cannot manipulate directly to an object, but must interact with that object.


Examples of two specific cases:

    • If the object is a large picture, it takes a long time to display, then when the picture is included in the document, use the editor or browser to open the document, open the document must be very fast, cannot wait for the big picture processing to complete, then need to do a picture proxy to replace the real picture.
    • If the object is on a remote server on the Internet and the object is directly manipulated because the network speed may be slow, then we can replace that object with proxy first.


The principle is that for a very expensive object to be created only when it is used, this principle can save us a lot of valuable Java memory. So, some people think that Java consumes resource memory, I think this and programming ideas also have a certain relationship.

How to use proxy mode

To Jive Forum System for example, access to the Forum system users have many types: registered ordinary users, forum managers, system managers, tourists. Register ordinary user can speak, forum Manager can manage his authorized forum, System Manager can manage all affairs, etc., these permission division and management is using proxy to complete.

Forum is the core interface of Jive, which displays the main actions of the forum, such as the name of the forum, the acquisition and modification of the forum description, and the deletion and editing of posts.

Users with various levels of permissions defined in Forumpermissions:

 Public classForumpermissionsImplementscacheable {/*** Permission to read object.*/ Public Static Final intREAD = 0;/*** Permission to administer the entire sytem.*/ Public Static Final intSystem_admin = 1;/*** Permission to administer a particular forum.*/ Public Static Final intForum_admin = 2;/*** Permission to administer a particular user.*/ Public Static Final intUser_admin = 3;/*** Permission to administer a particular group.*/ Public Static Final intGroup_admin = 4;/*** Permission to moderate threads.*/ Public Static Final intModerate_threads = 5;/*** Permission to create a new thread.*/ Public Static Final intCreate_thread = 6;/*** Permission to create a new message.*/ Public Static Final intCreate_message = 7;/*** Permission to moderate messages.*/ Public Static Final intModerate_messages = 8;..... Public Booleanissystemorforumadmin () {return(Values[forum_admin] | |values[system_admin]);} .....}

Therefore, the various operational permissions in forum are related to the user level defined by Forumpermissions, as the implementation of the interface forum: Forumproxy is the connection between this correspondence. For example, to modify the forum's name, only the Forums manager or system administrator can modify, the code is as follows:

 Public classForumproxyImplementsForum {Privateforumpermissions permissions; PrivateForum Forum;  This. Authorization =authorization;  PublicForumproxy (Forum Forum, Authorization Authorization, forumpermissions permissions) { This. Forum =Forum;  This. Authorization =authorization;  This. Permissions =permissions; }    .....     Public voidSetName (String name)throwsunauthorizedexception, forumalreadyexistsexception{//only the system or forum manager can modify the name    if(Permissions.issystemorforumadmin ()) {forum.setname (name); }Else{Throw Newunauthorizedexception (); }    }    ...}

And Dbforum is the real implementation of the interface forum, to modify the name of the forum as an example:

 public  class  dbforum "implements   Forum, cacheable {...  public  void  setName (String name) throws   Forumalreadyexistsexception {....   this . Name = name;  //  Here really saves the new name to the database   Savetodb ();    ....    } ...}

All involved in the Forum name modification this event, the other procedures are first to deal with Forumproxy, by Forumproxy decide whether have the authority to do something, Forumproxy is a veritable "gateway", "Security agent system".

In peacetime applications, there is always the need to involve the system of authorization or security system, whether you have the unconscious use of proxy, the actual you are already using proxy.

We continue to combine jive into a deeper point, the following involves the factory model.

We already know that the use of forum needs to create a forum through forumproxy,jive is to use the factory pattern, there is a total abstract class forumfactory, in this abstract class, Calling Forumfactory is implemented through the getinstance () method, where Singleton (also one of the design patterns) is used, and getinstance () returns FORUMFACTORYPROXY.

Why not return to Forumfactory and return to forumfactory implementation Forumfactoryproxy? The reason is obvious, and you need to determine whether you have permission to create a forum by proxy.

In Forumfactoryproxy we see the following code:

 Public classForumfactoryproxyextendsForumfactory {protectedForumfactory Factory;protectedAuthorization Authorization;protectedforumpermissions permissions; PublicForumfactoryproxy (Authorization Authorization, forumfactory factory,forumpermissions permissions) { This. Factory =Factory;  This. Authorization =authorization;  This. Permissions =permissions;}  PublicForum Createforum (string name, string description)throwsunauthorizedexception, forumalreadyexistsexception{//only system administrators can create forum    if(Permissions.get (forumpermissions.system_admin)) {Forum Newforum=factory.createforum (name, description); return NewForumproxy (newforum, authorization, permissions); }Else{Throw Newunauthorizedexception (); }    }}

Method Createforum Return is also forumproxy,proxy like a wall, other programs can only interact with proxy.

Notice that there are two proxy:forumproxy and Forumfactoryproxy. Represents two different responsibilities: using Forum and Creating forum. As for why the use of objects and the creation of objects is separated, this is why the use of the Factory mode is the reason: to "encapsulate" "dispatch". In other words, as much as possible function single, convenient maintenance modification.

Jive Forum System, such as the creation and use of posts, are in accordance with forum this idea.

Above we discussed how to use proxy for authorization mechanism access, Proxy can also hide the user another is called Copy-on-write optimization method. Copying a large and complex object is a costly operation, and if there is no modification to the original object during the copy process, then the copy overhead is not necessary. Delay this copy process with an agent.

For example: We have a very large collection, specifically such as Hashtable, there are many clients will concurrently access it. One of the special clients for continuous data acquisition requires that other clients no longer add or remove things to Hashtable.

The most straightforward solution is to use the collection lock to allow this particular client to obtain the lock, perform continuous data acquisition, and then release lock.

 Public void fofetches (Hashtable ht) {  synchronized(HT) {  /// specific continuous data acquisition action : }}


But this approach may lock collection for a long time, and during this time, other clients will not be able to access the collection.

The second solution is to clone the collection, and then let the continuous data get the collection operation for clone. The premise of this scenario is that the collection is clone and must have a way to provide deep clone. Hashtable provides the Clone method for itself, but not the key and value object.

 Public void fofetches (Hashtable ht) {hashttable newht=(Hashtable) Ht.clone ();}


The problem comes again, because it is for clone out of the object operation, if the original mother was modified by other client operations, then the clone out of the object operation is meaningless.

The Final Solution: we can wait for other clients to complete the modification before cloning, that is, this special client first by calling a method called Clone to perform a series of data acquisition operations. But there is actually no real copy of the object until other clients have modified the object collection.

Use proxy to implement this scenario, which is the copy-on-write operation.

Proxy application scope is very wide, now the popular distribution calculation method RMI and CORBA are the application of proxy mode.

Java Agent mode (proxy mode)

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.