Table of Contents
Agency mode: Static proxy
1. Definition of proxy mode
2. Advantages and disadvantages of the proxy model
3. Proxy Classification of patterns
4. The structure of the static proxy mode
5. Application scenarios of proxy mode
Home Java javaTutorial How to understand Java's proxy mode

How to understand Java's proxy mode

Apr 19, 2023 am 11:34 AM
java

    Agency mode: Static proxy

    Sometimes, we may not want to face something or someone directly, so we can find an intermediary Go and do things for us, such as sending gifts, calling for errands, finding a cleaner to go to a certain city, etc. In this way, the other party does not know who is involved behind the intermediary, and it plays the role of an intermediary and protects the target object. This is the agency model. That is to say, an intermediary does it for you.

    How to understand Java's proxy mode

    1. 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 cannot directly reference the target object, and the proxy object acts as an intermediary between the access object and the target object

    Simple structure diagram:

    How to understand Java's proxy mode

    2. Advantages and disadvantages of the proxy model

    Advantages:

    1. Plays an intermediary role between the client and the target object. The role of protecting the target object

    2. It can expand the function of the target object

    3. It can separate the client from the target object, which reduces the coupling of the system to a certain extent and increases the program complexity. Scalability

    Disadvantages:

    1. It will cause the number of classes in the system design to increase (because there are one or more intermediary classes (agents))

    2. Adding a proxy object between the client and the target object will slow down the request processing speed

    3. Increase the complexity of the system

    3. Proxy Classification of patterns

    The proxy pattern is divided into static proxy (this article) and dynamic proxy (next article) :

    • Static: The programmer creates the proxy class or a specific tool automatically generates the source code and then compiles it. The .class file of the proxy class already exists before the program runs

    • Dynamic: Created dynamically using the reflection mechanism when the program is running

    4. The structure of the static proxy mode

    1. Abstract theme class: Declares the business methods implemented by the real theme and proxy object through interfaces or abstract classes

    2. Real theme class: Implements the business methods in the abstract theme The specific business is the real object represented by the proxy object, which is the final object to be referenced

    3. Proxy class: Provides the same interface as the real topic, and contains internal references to the real topic Reference, which can access, control or extend the functionality of the real theme

    Code demonstration:

    Define an abstract theme:

    When using a static proxy, you need to define an interface or a parent class, and the proxy object and the proxy object implement the same interface or inherit the same parent class

    /**
     *抽象主题
     */
    
    public interface Subject {
        void Request();
    }
    Copy after login

    Real topic:

    /**
     *真实主题类:实现抽象主题
     */
    public class RealSubject implements Subject{
        @Override
        public void Request() {
            System.out.println("您的航班正在飞行");
        }
    }
    Copy after login

    Agent class:

    //代理类,实现抽象类的接口
    public class Proxy implements Subject{
    
        private RealSubject realSubject;
    
        @Override
        public void Request() {
            //先判断是否存在真实主题RealSubject
            //如果没有,就新建一个
            if(realSubject == null){
                realSubject = new RealSubject();
            }
    
            //预处理,使用这个方法
            preRequest();
    
            //去访问真实主题类的方法
            realSubject.Request();
    
            //代理类的后续方法
            postRequest();
        }
    
        private void preRequest() {
            System.out.println("航班马上起飞啦");
        }
    
        private void postRequest() {
            System.out.println("航班到达目的地,感谢乘坐");
        }
    
    
    }
    Copy after login

    Test class:

    public class Test {
        public static void main(String[] args) {
    
            //使用代理去访问RealSubject里面的Request
            Proxy proxy = new Proxy();
            proxy.Request();
        }
    }
    Copy after login

    Output result:

    The flight is about to take off
    Your flight is flying
    The flight has arrived at the destination, thank you for taking the flight

    Through the above demonstration, use a proxy class to access The method of the real theme class, so that the test class does not know who is accessing it, whether it is the proxy class or there are other people behind the proxy class, so that the object can be well protected. This is also the advantage of the agency model.

    Summary of static proxy:

    You can extend the target function without modifying the function of the target object, but the proxy object needs to be the same as the target object. Interface, so there will be many proxy classes. When there are many proxy classes, the maintenance complexity will become larger. So how to solve this problem? Then you need to use dynamic proxy.

    5. Application scenarios of proxy mode

    When you cannot or do not want to directly reference an object or there are difficulties in accessing an object, you can access it indirectly through a proxy object. There are two main purposes of using the proxy mode: One is to protect the target object, and the other is to enhance the target object

    The summary of this application scenario is referenced from the Internet:

    • Remote proxy, this method is usually used to hide the fact that the target object exists in a different address space to facilitate client access. For example, when a user applies for some network disk space, a virtual hard disk will be created in the user's file system. When the user accesses the virtual hard disk, he or she actually accesses the network disk space.

    • Virtual Agent , this method is usually used when the target object to be created is expensive. For example, downloading a large image takes a long time, and some calculations are complicated and cannot be completed in a short time. In this case, you can first replace the real object with a small-scale virtual agent to eliminate the user's feeling that the server is slow

    • Security proxy, this method is usually used to control the access rights of different types 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, add the function of counting the number of references to a real object, so that when the object is not referenced, it can be automatically released

    • Lazy loading refers to delaying the loading of the real object in order to improve the performance of the system. Target loading. For example, there is lazy loading of properties and lazy loading of related tables in Hibernate

    The above is the detailed content of How to understand Java's proxy mode. For more information, please follow other related articles on the PHP Chinese website!

    Statement of this Website
    The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

    Hot AI Tools

    Undresser.AI Undress

    Undresser.AI Undress

    AI-powered app for creating realistic nude photos

    AI Clothes Remover

    AI Clothes Remover

    Online AI tool for removing clothes from photos.

    Undress AI Tool

    Undress AI Tool

    Undress images for free

    Clothoff.io

    Clothoff.io

    AI clothes remover

    Video Face Swap

    Video Face Swap

    Swap faces in any video effortlessly with our completely free AI face swap tool!

    Hot Tools

    Notepad++7.3.1

    Notepad++7.3.1

    Easy-to-use and free code editor

    SublimeText3 Chinese version

    SublimeText3 Chinese version

    Chinese version, very easy to use

    Zend Studio 13.0.1

    Zend Studio 13.0.1

    Powerful PHP integrated development environment

    Dreamweaver CS6

    Dreamweaver CS6

    Visual web development tools

    SublimeText3 Mac version

    SublimeText3 Mac version

    God-level code editing software (SublimeText3)

    Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

    Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

    Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

    Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

    Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

    Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

    In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

    Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

    Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

    TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

    Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

    Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

    Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

    Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

    Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

    See all articles