Design mode series [21]: detailed explanation of agent mode (agent design mode)

In some cases, a customer cannot or does not want to directly access another object. At this time, it needs to find an intermediary to help complete a task. This intermediary is the proxy object. For example, you don't have to go to the railway station to buy train tickets. You can buy them through 12306 website or go to the train ticket agency. Another example is to find a girlfriend, a nanny, a job, etc. can be completed through an intermediary.

In software design, there are many examples of using proxy mode. For example, the remote object to be accessed is relatively large (such as video or large image), and its download takes a lot of time. In addition, for security reasons, it is necessary to shield the client from directly accessing the real object, such as the internal data of a unit.

Definition and characteristics of agent model

Definition of proxy mode: for some reasons, it is necessary to provide a proxy for an object to control access to the object. At this time, the access object is not suitable or can not directly reference the target object. The proxy object acts as an intermediary between the access object and the target object.

The main advantages of agent mode are:

  • Proxy mode plays an intermediary role between the client and the target object and protects the target object;
  • The proxy object can extend the function of the target object;
  • Proxy mode can separate the client from the target object, reduce the coupling of the system to a certain extent, and increase the scalability of the program.

Its main disadvantages are:

  • Agent mode will increase the number of classes in system design;
  • Adding a proxy object between the client and the target object will slow down the request processing speed;
  • It increases the complexity of the system.

So how to solve the shortcomings mentioned above? The answer is that you can use dynamic proxy

Structure and implementation of agent mode

The structure of proxy mode is relatively simple. It mainly includes real topics by defining an agent that inherits abstract topics, so as to access real topics. The following analyzes its basic structure and implementation methods.

1. Agency structure

The main roles of the agent mode are as follows:

  1. Abstract Subject class: business methods implemented by declaring real subjects and proxy objects through interfaces or abstract classes.
  2. Real Subject class: it implements the specific business in the abstract subject. It is the real object represented by the proxy object lock and the object to be referenced finally.
  3. Proxy class: provides the same interface as the real topic. It contains references to the real topic. It can access, control or extend the functions of the real topic.

Its structure is shown in the figure below:

In the code, the general agent will be understood as code enhancement. In fact, it is to add some code logic before and after the source code logic without the caller's perception.

According to the creation period of the agent, the agent mode is divided into static agent and dynamic agent:

  • Static: the programmer creates a proxy class or a specific tool to automatically generate the source code and then compile it. The proxy class is generated before the program runs The class file already exists.
  • Dynamic: it is created dynamically by using reflection mechanism when the program is running.

2. Implementation of mode

The implementation code of proxy mode is as follows:

package proxy;

public class ProxyTest {
    public static void main(String[] args) {
        Proxy proxy = new Proxy();

//Abstract theme
interface Subject {
    void Request();

//Real theme
class RealSubject implements Subject {
    public void Request() {
        System.out.println("How to access real topics...");

class Proxy implements Subject {
    private RealSubject realSubject;

    public void Request() {
        if (realSubject == null) {
            realSubject = new RealSubject();

    public void preRequest() {
        System.out.println("Preprocessing before accessing a real topic.");

    public void postRequest() {
        System.out.println("Subsequent processing after accessing the real topic.");

The results of program operation are as follows:

Preprocessing before accessing a real topic.
How to access real topics...
Subsequent processing after accessing the real topic.

Application example of agent mode

[example 1] Shaoguan "Tianjie e Jiao" company is an agency company of Wuyuan specialty company, which is realized by agency mode.

Analysis: the "Wuyuan specialty company" in this example operates many Wuyuan specialties. It is a real theme and provides a display() method for displaying specialties, which can be realized by form program. Shaoguan "Tianjie e corner" company is the agent of Wuyuan specialty company. It can display the agent products by calling the display() method of Wuyuan specialty company. Of course, it can add some additional processing, such as packaging or price increase. Customers can indirectly access the products of Wuyuan specialty company through the agent company of "e corner of Tianjie Street". Figure 2 shows the structure of the company.

The program code is as follows:

package proxy;
import java.awt.*;
import javax.swing.*;
public class WySpecialtyProxy {
    public static void main(String[] args) {
        SgProxy proxy = new SgProxy();
//Abstract theme: Specialty
interface Specialty {
    void display();
//Real theme: Wuyuan specialty
class WySpecialty extends JFrame implements Specialty {
    private static final long serialVersionUID = 1L;
    public WySpecialty() {
        super("Shaoguan agent Wuyuan specialty test");
        this.setLayout(new GridLayout(1, 1));
        JLabel l1 = new JLabel(new ImageIcon("src/proxy/WuyuanSpecialty.jpg"));
    public void display() {
//Agent: Shaoguan agent
class SgProxy implements Specialty {
    private WySpecialty realSubject = new WySpecialty();
    public void display() {
    public void preRequest() {
        System.out.println("Shaoguan agent Wuyuan specialty began.");
    public void postRequest() {
        System.out.println("Shaoguan agent Wuyuan specialty finished.");

The program running results are shown in the following figure:

Application scenario of agent mode

When you cannot or do not want to directly reference an object or have difficulty accessing an object, you can access it indirectly through a proxy object. There are two main purposes of using proxy mode: one is to protect the target object, but to enhance the target object.

After analyzing the structure and characteristics of agent mode, let's analyze the following application scenarios:

  • Remote proxy is usually used to hide the fact that the target object exists in different address spaces and facilitate client access. For example, when users apply for some network disk space, a virtual hard disk will be established in the user's file system. When users access the virtual hard disk, they access the network disk space.
  • Virtual proxy, this method is usually used to create target objects when the cost is large. For example, it takes a long time to download a large image, which cannot be completed in a short time due to the complexity of some calculation. At this time, a small proportion of virtual agents can be used to replace the real object to eliminate the user's feeling of slow server.
  • Security agent, which is usually used to control the access rights of different kinds of customers to real objects.
  • Intelligent guidance is mainly used to add some additional processing functions to the agent when calling the target object. For example, increase the function of calculating the number of references of a real object, so that when the object is not referenced, it can be automatically released.
  • Delayed loading refers to delaying the loading of targets in order to improve the performance of the system. For example, there are delayed loading of attributes and associated tables in Hibernate.

Extension of agent mode

In the proxy pattern introduced earlier, the proxy class contains references to real topics, which has two disadvantages.
The real theme corresponds to the agent theme one by one. Adding a real theme also requires adding an agent.
Before the design agent, the real theme must exist in advance, which is not very flexible. The above problems can be solved by using the dynamic proxy mode, such as spring AOP. Its structure diagram is shown in the figure below.

Keywords: Design Pattern

Added by 00Sven on Wed, 22 Dec 2021 14:41:20 +0200