Proxy Pattern)

Source: Internet
Author: User

Proxy Pattern)

In this blog, we will explain in detail the Proxy Pattern, including the definition, role, and detailed design and analysis of the Proxy Pattern.
I. Pattern name

Provides a proxy for other objects to control access to this object. -- The basis for reusable object-oriented software in Design Patterns

Ii. Problem

Have you ever encountered the following problems in your daily work and programming:

You have created a webpage with your thoughts on life and your insights on life. You have carefully selected some exquisite pictures or illustrations for the beauty of the whole page, overall looks very good! However, you may find that when the network is poor and the network status is good, the whole page loading will be slow and the user experience will be poor. However, you do not want to discard the carefully selected images, so you have to worry about it for a long time and cannot find a proper solution.

When you create a website, you need to set different permissions for different users (visitors, registered common users, member users, system administrators, and website administrators, if you design them into different functional classes separately, and you find that there are many similar or even identical functions among different users, the whole system looks like code duplication is serious. How can we design it smartly, does it not only reflect different permissions of different users, but also effectively reduce code duplication?

If you often encounter the problems described above and cannot solve them, You should make friends with the proxy mode and learn to use the proxy mode to solve the above problems and other problems.

Iii. Solution

First, let's take a look at the UML class diagram structure of the proxy mode:

It is the most basic and simple proxy mode. We can see that Subject represents an abstract class or interface, which defines the methods to be called by the Client, the RealSubject class is the real implementation class of this method. Although the Proxy inherits the Subject abstract class or implements the Subject interface, it is not actually implemented in the Proxy, instead, generate a reference RealSubject to the realSubject object, and then call realSubject. request () to implement the method required in the Subject, that is, the Request () method.

Here, we can use an image analogy: the Proxy mode actually tells us that the Proxy is actually a live connection, while the real work is RealSubject, but the customer (Client) you don't need to know who is actually working. He just needs to create a Proxy object through Subject myProxy = new Proxy (); and then call myProxy. request (); method to achieve your own requirements, you can. The Client is not concerned about whether the Proxy is working by itself or finding someone to work. He only cares about whether the tasks he has arranged have been completed.

In fact, the proxy mode has a lot of deformation, and the design process is flexible. It can solve many problems through proper deformation. Next we will try to use the proxy mode to solve the two problems we just proposed.

1. page loading problems:

First, let's take a look at the UML class diagram structure of the page loading problem solution:

We can find that the load control program of the entire page is actually equivalent to (effecenteditor), and it does not directly create an Image (the real implementation class of Image operations) object, instead, a proxy object (ImageProxy) is created through the Graphic interface, which stores the most basic information of the image, such as the image name (fileName ), the Image size (extent). In this way, when loading a page, you do not need to create an Image object immediately when you need to adjust the layout of elements in the page, you only need to create a proxy object (ImageProxy) and use the extent attribute of the proxy object to complete the layout of the interface. When the page has been moved to the Image location (as shown in the following figure), call the Draw () method of ImageProxy. Then, a new Image object is created by the proxy object (ImageProxy, and call the Draw () method of the Image object.

That is to say, the image proxy (ImageProxy) is only available when the page load controller activates (CALLS) the Draw () Operation of the image proxy (ImageProxy) to display this image) then, the Image proxy forwards the Draw () request to the real Image object.

This can effectively delay the creation time of the Image object. If the creation time of the Image object is very long, it will effectively reduce the effect of the creation of the Image object on the loading speed of the entire page, this effectively solves the slow page loading problem we mentioned above.

2. Website permission Control Problems

The UML class diagram interface for website permission control is similar to the above page loading problem. We will not draw a UML class diagram and directly use the code.

Abstract class or interface (Subject) code:

Public interface Subject {// public void operation ();}

RealSubject code:

Public class RealSubject implements Subject {public void operation () {// The real implementation class operation System. out. println ("this is the real implementation class operation. ");}}

Proxy code:

Public class Proxy implements Subject {RealSubject realSubject = new RealSubject (); // Of course, Subject realSubject = new RealSubject (); public void operation () {// before calling the object method that actually implements the operation, you can perform the operation before the call. System. out. println ("here, you can perform some pre-call operations. "); RealSubject. operation (); // after calling the object method that actually implements the operation, you can perform the operation after the call. System. out. println ("here, you can perform some post-call operations. ");}}

Client code:

public class Client {    public static void main(String[] args) {        Subject myProxy = new Proxy();        myProxy.operation();    }}

The code above is easy to understand. Here, I mainly explain the Proxy code. From the code, we can see that realSubject is called. operation (); previously, you can perform processing before calling, such as checking permissions and checking environment conditions. After calling, you can also perform corresponding processing. Of course, if you feel that some users cannot call this method based on user permissions, and you do not have the permission to call this method, the system will return a reminder, for example, "Please view it after login. You can reengineer the Proxy's operation method, use a judgment statement to determine user permissions, and then choose not to execute realSubject based on the judgment result. operation () method, how to execute this method, and whether to return warning information.

Now, we have solved the two problems mentioned above. Have you found out the charm of the proxy mode slowly!

Iv. Consequences

It can be said that by adding a proxy, We can greatly increase the flexibility of controlling this object, and we can increase the control and protection we need in accessing and operating the object.

So we have said that the proxy mode is flexible, has many variants, and has many application scenarios. So what are the variants and scenarios in which they are used? Here is a brief introduction:

(1) Remote Proxy-you can hide the fact that an object exists in a different address space. The client can also access objects on a remote machine. The remote machine may have better computing performance and processing speed, and can quickly respond to and process client requests.

(2) Virtual Proxy-allows objects with high memory overhead to be created as needed. This object is created only when we really need it (in fact, this is similar to the question we raised about page loading ).

(3) Copy-On-Write Proxy (Copy-On-Write Proxy)-used to control object replication by delaying object replication until the customer really needs it. Is a variant of the virtual proxy.

(4) Protection Proxy-provide different levels of target object Access permissions for different customers

(5) Cache Proxy-provides temporary storage for overhead computing results. It allows multiple customers to share results to reduce computing or network latency.

(6) Firewall Proxy-controls access to network resources and protects the subject from malicious customer attacks.

(7) SynchronizationProxy-Provides secure access to the topic in the case of multiple threads.

(8) Smart ReferenceProxy-provides some additional operations when an object is referenced, such as recording the number of calls to this object.

(9) Complexity HidingProxy: used to hide the Complexity of a complex set of classes and perform access control. It is also called the appearance proxy (Fa? Ade Proxy), which is not hard to understand. The complex hidden proxy and appearance mode are different because the proxy controls access, while the appearance mode is different because the proxy controls access, while the appearance mode only provides another set of interfaces.

Here we will explain in detail how to optimize copy-on-write:

This optimization is related to the creation of objects as needed. copying a large and complex object is a costly operation. If the copy is not modified at all, these overhead are unnecessary, using proxy to delay this copy process ensures that this object is copied only when it is modified.

When implementing copy-on-write, the object must be referenced and counted. The copy proxy only increases the reference count. Only when the user requests to modify the object, the proxy will actually copy the object. In this case, the proxy must also reduce the reference count of the object. When the number of references is 0, the object will be deleted.

5. FAQs and others

Question 1: do I use RealSubject = new realSubject (); or use Subject RealSubject = new realSubject (); when creating RealSubject objects in the Proxy ();? Actually, that is to say, should the Proxy hold a Subject object or a RealSubject object?

When I was learning this model, I had such questions. I saw a lot of code, some of which were the first method, and some were the second method. Which method is better? In fact, it depends on the situation.

Scenario 1:If all the methods declared in Subject (abstract class or interface) are the same as all the methods provided by RealSubject, both methods can be declared in principle. However, considering the interface-oriented programming principle rather than implementation-oriented programming, it would be better to declare as Subject realSubject; that is, to hold a Subject object.

Scenario 2:If you want to implement a Proxy class that can Proxy multiple implementation classes at the same time without modifying the Proxy, the Proxy uses Subject RealSubject; that is, it holds a Subject object, it will be much better. In addition, we need to specify in the Proxy constructor which implementation class it refers to (RealSubject ). In this way, when creating a proxy object, the Client needs to input an object that he wants to operate through the proxy. For example:

Proxy code:

public class Proxy implements Subject{    private Subject realSubject;    public Proxy(Subject realSubject){            this.realSubject = realSubject;    }}

Client code:

Subject realSubject1 = new RealSubject1();Subject realSubject2 = new RealSubject2();Subject proxy1 = new Proxy(realSubject1);Subject proxy2 = new Proxy(realSubject2);

Some people may wonder why the Client does not directly call the methods provided in a specific implementation class since the Client has obtained the RealSubject object? Moreover, it is easy to give the object of a specific implementation class to the Client. Isn't it allowed the Client to perform some illegal operations on the specific implementation class?

As a matter of fact, you are right. This kind of defect does occur, but we can eliminate it through further design. We can package another layer of Proxy outside RealSubject, or directly add a layer of Judgment Processing in RealSubject to determine whether the source of the method to be called is a Proxy. If it is not a Proxy, access is denied. That is, make RealSubject only accept method calls from Proxy. This solves the problem, but it seems a bit complicated.

Case 3:If RealSubject provides more methods than those defined in Subject, or the methods defined in RealSubject are different from those defined in Subject, at this time, the main function of Proxy may be to hide complex operations of RealSubject, or the Proxy can implement functions only when calling methods that exist in RealSubject and do not exist in Subject, declared as RealSubject realSubject = new RealSubject (); that is, it is more appropriate to hold a RealSubject object. Common applications include packaging database operations and providing database proxies.

Question 2: How to implement a Proxy class without changing, and then assign different RealSubject objects to the Proxy, that is, different implementation classes.

For the answer to this question, please refer to case 2 in question 1.

Question 3: How to implement a RealSubject class that corresponds to different proxies, that is, to implement the same object, different Proxy methods, or Proxy functions?

As for this problem, the different proxy methods or proxy functions to be implemented are not very different. You can consider adding control code to the original proxy class. Of course, if the difference is great, or to better practice the OCP principle, you can add a proxy class responsible for the Implementation class, or add a new proxy class responsible for the original proxy class, and then in the newly added proxy class, make modifications and designs accordingly.

Vi. Summary

Here, our explanation of the proxy mode has come to an end. As I mentioned earlier, the proxy category involves a wide range and is not limited to the ones we discussed above. In addition, there are many other aspects that need to be learned and applied.

Special emphasis should be placed on the consideration and analysis of the dynamic proxy model,Due to space and time issues, we will continue to learn about the dynamic proxy mode analysis in the future design patterns blog series. Similarly, if you have any questions or good suggestions, please leave a message and we will study and make progress together.

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.