This is the fourth day of my participation in the August More text Challenge. For details, see:August is more challenging

Welcome to today’s study. Today we are going to learn about the agent model that is used very frequently. More words, this month will be on the Java design patterns in detail, welcome to click on the profile picture, follow my column, I will keep updating, come on!

Series of articles:

Singletons of design patterns

The factory model of design pattern

The builder pattern of design patterns

. Under continuous update

Without further ado, let’s get to the point

The proxy pattern

Proxy Pattern, also known as delegate Pattern, is a highly used Pattern. When you see a Proxy name in your code, you must be using Proxy mode

As the name suggests, is this from the middle to do the next agent, just a “middleman”, in our life, for example, you rent, buy a house, certainly not directly with the landlord or real estate to directly talk. So the position of “intermediary” was born. This is the case with the agency model.

We often use VPN, is the classic case of proxy mode (commonly known as over the wall), the server has no access to the external network, no external network port, are installed in the server VPN software, the external network through the VPN software login, can access.

I personally like a sentence: no function and requirement can not be realized, if there is, then add a layer, this layer is similar to the meaning of the agent. Layer upon layer encapsulation, layer upon layer agent. Requirements and conditions can be easily implemented

The proxy pattern is a basic design technique, and many other patterns, such as the state pattern, the policy pattern, and the visitor pattern, adopt the proxy pattern in nature. Personally, I think this is the foundation.

In the figure above we see ProxySubject which points to Subject and RealSubject respectively.

There are generally three types of roles in the agency model:

  • Abstract (Subject) role, which is the common interface between the real topic and the broker topic so that the broker topic can be used wherever the real topic can be used.

  • The Proxy Subject role, also known as the delegate class or Proxy class, controls references to the real Subject, creates or deletes real Subject objects as needed, and preprocesses and postprocesses the real Subject role before and after it is processed.

  • Real Subject role: This role, also known as the delegated or deputized role, is the implementer of the business logic.

Let’s take a closer look at the code

The code shown

public interface Subject{
    // Define a request
    public void request(a);
}
Copy the code

True role

// Real characters
public Class RealSubject implements Subject{
    @Override
    public void request(a){
        // Output logic, specific business executor}}Copy the code

The code for the ProxySubject ProxySubject is shown below.

/ / the proxy class
public class ProxySubject implements Subject {
       private subject subject;

       public ProxySubject (Subject subject) {
           this.subject = subject;
       } 
       
       // Implement the request method
       public void request(a) {
            this.beforeRequest();
            subject.request();
            this.afterRequest();
       }
        
       // Pre-request processing
       private void beforeRequest(a){}// Request post-processing
       private void afterRequest(a){}}Copy the code

A proxy topic class can proxy multiple real topics. The specific real topic to proxy is determined by the high-level application module, and can be passed to the proxy class constructor.

Why use the proxy pattern

After watching the above, you may ask why you use proxy mode. Because it doesn’t feel very useful. No.

There are two more important reasons.

  1. Sometimes clients cannot directly manipulate certain objects. For example, in a distributed application, the object you need to call may be running on another server, and when you access it, you have to access it over the network. If you let the client to call directly, that means the client need to deal with network service, then we in the proxy pattern, the client and establish a network proxy objects between the remote server, the client just call can establish contact with the remote object proxy objects, even like calls to local objects. This is essentially the rationale for what we call RPC services, essentially the proxy pattern.

  2. The server must control the access permission of the client. In addition to the extension functions mentioned earlier, another more important function of the proxy pattern is permission control. For example, a certain business can only be accessed by some specific users due to security reasons. If the permission filtering function is added on the basis of the original function, the coupling of code will be increased, and the reuse of components will not be convenient. In fact, making a proxy class can solve this problem. For a specific interface, you only need to specify that all requests must pass through the proxy class, and then the proxy class does the permission judgment.

Classification and application scenarios

  • The first type, virtual proxies, is suitable for delayed initialization and small objects representing large objects: The Implementation of the CopyOnWriteArrayList array object in Java uses virtual proxies to delay the operation and clone the object only when it is actually used.

  • The second type, protected agents, applies to scenarios in which the server controls access to the client. The permission control mentioned above, such as firewalls, is actually a specific practice of protecting agents.

  • The third category, remote agent, is suitable for scenarios where remote service code needs to be executed locally, such as remote agent frameworks, such as gRpc, Dubbo, etc.

  • The fourth category, logging agents, is suitable for scenarios where you need to keep a history of the request object, which I think is the most common category in our practical use, using an AOP aspect to load beans into Spring, for example, logging monitoring. The client is not aware of the logging when the request is invoked because the proxy object adds monitoring capabilities around the original object.

  • The fifth category, the cache proxy, is suitable for scenarios where the results of customer requests are cached and the cache lifecycle is managed. For example, a commodity detail page often contains a large number of images and text descriptions, and the proxy object can cache the same results for repeated requests.

conclusion

Here’s a summary of what the agency model tries to solve:

  • Some objects cannot be called directly;

  • An interface may require additional external operations, such as logging, permission control, and repeated operations.

  • Access permissions need to be controlled.

overtones

OK, so much for today’s agent mode, thank you for reading, if you feel learned something, please click like, attention.

I have included this chapter in my project, click on the project below, and follow the column. I will publish dry items every day, and I will continue to enter design patterns this month.

Come on! See you next time