Design Pattern pocket edition continuous reprinting-proxy)

Source: Internet
Author: User
Original: fanix

Understanding and using the design pattern can cultivate our good Object-Oriented Programming habits. At the same time, in practical applications, we can enjoy the fun.

Proxy is a more useful mode with many variants. The application scenario covers the large structure from the small structure to the entire system. Proxy is the meaning of proxy. We may have concepts such as proxy server, the proxy concept can be interpreted as: there is an intermediate layer between the starting point and the destination, meaning the proxy.

Defined in the design mode: provides a proxy for other objects to control access to this object.

Why use proxy?
1. users of different levels of authorization mechanisms have different access rights to the same object. For example, in the jive forum system, proxy is used to control the authorization mechanism. There are two types of users who access the Forum: registered users and tourists (unregistered users), jive uses a proxy like forumproxy to control the access permissions of these two users to the Forum.

2. A client cannot directly operate on an object, but must interact with the object.
Two specific cases are given:
(1) if the object is a large image that takes a long time to be displayed, when the image is included in the document, open the document using the editor or browser, opening a document must be fast and cannot wait until the processing of the large image is completed. In this case, you need to create an image proxy to replace the real image.

(2) if the object is on a remote server on the internet, it may be slow to directly operate on the object because of the network speed, we can replace the object with a proxy.

In short, the principle is that objects with high overhead are created only when they are used. This principle can save us a lot of valuable Java memory. therefore, some people think that Java consumes resources and memory. I think this is also related to programming ideas.

How to use proxy?
Take the jive forum system as an example. There are multiple types of users accessing the forum system: Registered ordinary users, Forum managers, system administrators, visitors, registered ordinary users, can speak; Forum managers can manage their authorized forums; system Administrators can manage all transactions. These permissions are divided and managed using proxy.

As the core interface of jive, Forum displays the main activities related to Forum operations in forum, such as obtaining and modifying Forum name descriptions, posting, deleting, and editing posts.

Users with various levels of permissions are defined in forumpermissions:
Program code:

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 particle forum.
*/
Public static final int forum_admin = 2;

/**
* Permission to administer a participant user.
*/
Public static final int user_admin = 3;

/**
* Permission to administer a participant 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 Operation permissions in Forum are related to the user level defined by forumpermissions. As the implementation of the Forum interface, forumproxy associates the corresponding relationship. for example, to modify the Forum name, only the forum manager or system manager can modify the name. The Code is as follows:
Program code:

Public class forumproxy implements Forum {

Private forumpermissions permissions;
Private forum Forum;
This. Authorization = authorization;

Public forumproxy (forum Forum, 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 administrator can modify the name.
If (permissions. issystemorforumadmin ()){
Forum. setname (name );
}
Else {
Throw new unauthorizedexception ();
}
}

...

}

 

Dbforum is the real implementation of the Forum interface. The following uses modifying the Forum name as an example:

Public class dbforum implements Forum, cacheable {
...

Public void setname (string name) throws forumalreadyexistsexception {

....

This. Name = Name;
// Save the new name to the database
Savetodb ();

....
}

...

}
 

When it comes to modifying the Forum name, other programs must first deal with forumproxy. forumproxy decides whether to have the permission to do the same thing. forumproxy is a real "Gateway ", "Security Proxy system ".

In normal applications, it is inevitable that the authorization or security system of the system is always involved. No matter whether you use proxy unconsciously, you are actually using proxy.

Let's continue to talk more deeply with jive. The following describes the factory model. If you do not know about the factory model, please read another article: Factory

We already know that to use forum, you need to create a forum in forumproxy through forumproxy. In jive, the Forum mode is used, and there is a general abstract class forumfactory. In this abstract class, the forumfactory is called through getinstance () method implementation. Singleton is used here (it is also one of the design patterns. As there are many articles introduced, I will not write it. Here). getinstance () returns forumfactoryproxy.

Why does the forumfactory Implementation of forumfactoryproxy not be returned?
The reason is obvious. You need to use a proxy to determine whether you have the permission to create a forum.

In forumfactoryproxy, the Code is as follows:
Program code:

Public class forumfactoryproxy extends forumfactory {
Protected forumfactory factory;
Protected authorization;
Protected forumpermissions permissions;

Public forumfactoryproxy (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 the system administrator can create a forum
If (permissions. Get (forumpermissions. system_admin )){
Forum newforum = factory. createforum (name, description );
Return new forumproxy (newforum, authorization, permissions );
}
Else {
Throw new unauthorizedexception ();
}
}

 

The method createforum returns forumproxy, which is like a wall. Other programs can only interact with the proxy.

Note that there are two proxies: forumproxy and forumfactoryproxy. representing two different responsibilities: Using forum and creating forum;
The reason for separating the object used from the created object is also the reason for using the factory mode: To "encapsulate" "dispatch"; in other words, to simplify the functions as much as possible to facilitate maintenance and modification.

The creation and use of other posts in the jive forum system follow the forum idea.

We have discussed how to use proxy to access the authorization mechanism. Proxy can also hide another optimization method called copy-on-write to users. copying a large and complex object is a costly operation. If the original object is not modified during the copy process, this copy overhead is unnecessary. use a proxy to delay this copy process.

For example, we have a large collection, such as hashtable. Many clients access it concurrently. one of the special clients needs to obtain continuous data. In this case, other clients are required not to add or delete data to or from hashtable.

The most direct solution is to use the Lock of collection to allow this special client to obtain the lock, perform continuous data acquisition, and then release the lock.
Program code:

Public void fofetches (hashtable HT ){
Synchronized (HT ){
// Specific actions for obtaining continuous data ..
}

}

However, this method may take a long time to lock the collection. During this period, other clients will not be able to access the collection.

The second solution is to clone the collection, and then let the continuous data obtain the cloned collection operation. the premise of this solution is that the collection can be cloned, and there must be a method to provide deep clone. hashtable provides its own clone method, but it is not a clone of key and value objects. For details about the clone meaning, refer to the special article.
Program code:

Public void fofetches (hashtable HT ){

Hashttable newht = (hashtable) Ht. Clone ();

}

The problem arises again because it is for clone object operations. If the original parent object is modified by other client operations, the cloned object operations will be meaningless.

Final Solution: we can wait for other clients to complete the modification before cloning. That is to say, this special client first calls a method called clone to perform a series of data acquisition operations. but the object is not actually copied until another client modifies the object collection.

Use proxy to implement this scheme. This is the copy-on-write operation.

Proxy has a wide range of applications. Currently, popular distributed computing methods such as RMI and CORBA are proxy-based applications.

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.