Proxy mode (java)

Table of contents

structure

Static proxy case

 Code

Ticketing

Train station

Proxy class

test class

Advantages and disadvantages

advantage

shortcoming


structure

The Proxy mode is divided into three roles:

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

  • Real Subject (Real Subject) class : realizes the specific business in the abstract subject, is the real object represented by the proxy object, and is the final object to be referenced.

  • Proxy (Proxy) class : Provides the same interface as the real theme, which contains references to the real theme, which can access, control or extend the functions of the real theme.

Static proxy case

[Example] selling tickets at a train station

If you want to buy a train ticket, you need to go to the train station to buy the ticket, take the train to the train station, wait in line and wait for a series of operations, which is obviously more troublesome. And the railway station has sales offices in many places, so it is much more convenient for us to go to the sales offices to buy tickets. This example is actually a typical agent model, the train station is the target object, and the sales agency is the agent object.

 Code

Ticketing

package static_proxy;

/**
 * @author: ZQH
 * @project: Design Pattern
 * @description 售票类
 * @date: 2023/7/20 15:28
 */
public interface SellTickets {
    void sell();
}

Train station

package static_proxy;

/**
 * @author: ZQH
 * @project: Design Pattern
 * @description 火车站类
 * @date: 2023/7/20 15:29
 */
public class TrainsStation implements SellTickets {

    @Override
    public void sell() {
        System.out.println("火车站买票");
    }

}

Proxy class

package static_proxy;

/**
 * @author: ZQH
 * @project: Design Pattern
 * @description 售票代理
 * @date: 2023/7/20 15:30
 */
public class TicketsProxy implements  SellTickets {

    private final TrainsStation trainsStation = new TrainsStation();

    @Override
    public void sell() {
        System.out.println("收取售票手续费");
        trainsStation.sell();
    }

}

test class

package static_proxy;

/**
 * @author: ZQH
 * @project: Design Pattern
 * @description 测试类
 * @date: 2023/7/20 15:27
 */
public class Client {
    public static void main(String[] args) {

        // 实例化代理商
        TicketsProxy proxy = new TicketsProxy();
        // 代理商买票
        proxy.sell();

    }

}

Advantages and disadvantages

advantage

  • The proxy mode plays an intermediary role between the client and the target object and protects the target object .

  • A proxy object can extend the functionality of a target object.

  • The proxy mode can separate the client from the target object, reducing the coupling of the system to a certain extent .

shortcoming

  • Increased system complexity.

Guess you like

Origin blog.csdn.net/qq_51179608/article/details/131852257