Introduction to the proxy mode (proxy mode) of the Java design pattern _java

Source: Internet
Author: User

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

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

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

Why to use proxy mode

1. 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 types of people: Registered users and visitors (unregistered users), In Jive, a proxy like forumproxy is used to control the access of both users to the forum.
2. A client cannot directly manipulate an object, but must interact with that object.

Examples of two specific situations:

1. If that object is a very large picture, it takes a long time to be displayed, so when the picture is included in the document, you open the document using an editor or a browser, and the document must be opened quickly, and you can't wait for the big picture to finish, then you need to do a picture proxy instead of the real picture.
2. If the object is on a remote server on the Internet, direct manipulation of the object because the network speed may be slow, then we can use proxy to replace that object.

In short, the principle is that for a very expensive object, it is created only when it is used, which saves 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 a variety of types: registered ordinary users, forum managers, system managers, tourists. Registered ordinary users can speak, forum managers can manage his authorized forum, system managers can manage all transactions, and so on, these rights division and management is done using proxy.

Forum is the core interface of Jive, which displays the main behavior of forum operation in forum, such as forum name, access and modification of forum description, post deletion edit, etc.

Users who have defined various levels of permissions in Forumpermissions:

Copy Code code as follows:

public class Forumpermissions implements cacheable {
/**
* Permission to read object.
*/
public static final int READ = 0;

/**
* Permission to administer the entire sytem.
*/
public static final int system_admin = 1;

/**
* Permission to administer a particular forum.
*/
public static final int forum_admin = 2;

/**
* Permission to administer a particular user.
*/
public static final int user_admin = 3;

/**
* Permission to administer a particular group.
*/
public static final int group_admin = 4;

/**
* Permission to moderate threads.
*/
public static final int moderate_threads = 5;

/**
* Permission to create a new thread.
*/
public static final int create_thread = 6;

/**
* Permission to create a new message.
*/
public static final int create_message = 7;

/**
* Permission to moderate messages.
*/
public static final int moderate_messages = 8;

.....

public Boolean issystemorforumadmin () {
Return (Values[forum_admin] | | | values[system_admin]);
}

.....

}

Therefore, the various operational permissions in forum are related to the user level defined by Forumpermissions as an interface forum implementation: Forumproxy is the link between this correspondence. For example, to modify the name of the forum, only the Forum manager or System Manager can modify the code as follows:

Copy Code code as follows:

public class Forumproxy implements Forum {
Private forumpermissions permissions;
Private Forum Forum;
This.authorization = authorization;

Public Forumproxy (Forum Forum, Authorization Authorization,
Forumpermissions permissions) {
This.forum = Forum;
This.authorization = authorization;
this.permissions = permissions;
}
.....
public void SetName (String name) throws Unauthorizedexception,
forumalreadyexistsexception{
Only the system or forum manager can modify the name
if (Permissions.issystemorforumadmin ()) {
Forum.setname (name);
}
else {
throw new Unauthorizedexception ();
}
}
...

}

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

Copy Code code as follows:

public class Dbforum implements Forum, cacheable {
...
public void SetName (String name) throws Forumalreadyexistsexception {
....
THIS.name = name;
This really saves the new name to the database
Savetodb ();
....
}
...
}

All involved in the name of the forum to modify this event, the other procedures have to deal with Forumproxy first, by Forumproxy decide whether have permission to do something, Forumproxy is a veritable "gateway", "Security agent system."

In peacetime applications, inevitably involves 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 to talk deeply, the following will involve the factory model.

We already know that using forum requires creating a forum through Forumproxy,jive is using the factory pattern, there is a total abstract class forumfactory, in this abstract class, The call Forumfactory is implemented through the getinstance () method, where Singleton (also one of the design patterns) is used, and getinstance () returns FORUMFACTORYPROXY.

Why not return the forumfactory and return the forumfactory implementation forumfactoryproxy? The reason is obvious, and it is up to the broker to determine if there is permission to create forum.

In Forumfactoryproxy we see the code as follows:

Copy Code code as follows:

public class Forumfactoryproxy extends Forumfactory {
protected Forumfactory Factory;
protected Authorization Authorization;
protected forumpermissions permissions;

Public Forumfactoryproxy (Authorization Authorization, forumfactory factory,forumpermissions permissions) {
This.factory = Factory;
This.authorization = authorization;
this.permissions = permissions;
}

Public Forum Createforum (string name, string description)
Throws Unauthorizedexception, forumalreadyexistsexception{
Only system administrators can create forum
if (Permissions.get (forumpermissions.system_admin)) {
Forum newforum = factory.createforum (name, description);
return new Forumproxy (Newforum, authorization, permissions);
}
else {
throw new Unauthorizedexception ();
}
}
}

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

Note 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 separate, which is why the use of the Factory mode is the reason: to "encapsulate" "allocation." In other words, function single as much as possible to facilitate maintenance modification.

Jive Forum System in other such as the creation and use of posts, are based on forum this idea.

We discussed how to use proxy to access the authorization mechanism, and the proxy can also hide another optimization method called Copy-on-write for the user. Copying a large and complex object is a costly operation, and if the original object is not modified in the copy process, then the copy overhead is unnecessary. Delay this copy process with a proxy.

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, at this time require other clients can no longer add or remove Dongdong to the Hashtable.

The most straightforward solution is to use collection lock to have this particular client get this lock, make continuous data acquisition, and then release lock.

Copy Code code as follows:

public void Fofetches (Hashtable ht) {
Synchronized (HT) {
Specific continuous data acquisition action.
}
}

But this method may be locked collection will be a long time, this time, other clients will not be able to access the collection.

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

Copy Code code as follows:

public void Fofetches (Hashtable ht) {
Hashttable newht= (Hashtable) Ht.clone ();
}

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

Final Solution: We can wait for other clients to modify and then clone, that is to say, this special client first by invoking a method called Clone to do a series of data acquisition operations. But actually there is no real copy of the object until another client modifies the object collection.

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

The application scope of proxy is very wide, and the popular distribution computing methods RMI and CORBA are the application of proxy mode.

Related Article

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.