Design Pattern 6 Agent Mode

Regarding the agency model, it is easy to understand. For example, if you buy a concert ticket, it is difficult to buy it yourself. You can only go to the scalper. The scalper is the agent (unofficial) selling train tickets.

In development, the proxy model is very common. Objects of a class are not generated directly, and objects are generated for you through proxy classes. Then the function of the object generated by the proxy may be enhanced. Generally, if we want to enhance the function of an object, we can use the proxy mode.

What is the proxy model

Provide a surrogate or placeholder for another object to control access to it. (Provide a proxy for other objects to control access to this object.)

I think the proxy model has several useful functions:

  • Can protect the target object, we do not directly access the target object, but through the proxy object

  • The proxy object can extend the functionality of the target object

The client cannot directly access the target object, but can only access it through the proxy object, which will inevitably reduce the access speed. At the same time, proxy objects are added, and the complexity of the system is also increased.

So what are the elements of the agency model?

  1. Abstract subject (Subject) class: Declare business methods implemented by real subjects and proxy objects through interfaces or abstract classes.

  2. Real Subject class: It implements the concrete business in the abstract subject. It is the real object represented by the proxy object and the object to be eventually referenced.

  3. Proxy class: Provides the same interface as the real theme. It contains references to the real theme. It can access, control or extend the functions of the real theme.

The relationship between these elements is as follows:

Agency model

Code

Here is the code:

Subject

public interface Subject {
    void request();
}

Proxy

public class Proxy implements Subject {

    private RealSubject realSubject;

    @Override
    public void request() {
        if (realSubject == null) {
            realSubject = new RealSubject();
        }
        preRequest();
        realSubject.request();
        postRequest();
    }

    public void preRequest() {
        System.out.println("访问真实主题之前的预处理!!!");
    }

    public void postRequest() {
        System.out.println("访问真实主题之后的后续处理!!!");
    }
}

RealSubject

public class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("真实类访问方法!!!!");
    }
}

The test is as follows:

public class ProxyTest {
    public static void main(String[] args){
        Proxy proxy = new Proxy();
        proxy.request();
    }
}
访问真实主题之前的预处理!!!
真实类访问方法!!!!
访问真实主题之后的后续处理!!!

About dynamic agents

For more advanced applications of proxy mode, please refer to this article of mine:

The dynamic agent you must ask in interviews

 

Guess you like

Origin blog.csdn.net/wujialv/article/details/109020806