This is the 13th day of my participation in the November Gwen Challenge. Check out the event details: The last Gwen Challenge 2021

Author’s other platforms:

| CSDN:blog.csdn.net/qq\_4115394…

| the nuggets: juejin. Cn/user / 651387…

| zhihu: www.zhihu.com/people/1024…

| GitHub:github.com/JiangXia-10…

| public no. : 1024 notes

This article is about 3,947 words and takes 10 minutes to read

define

The proxy pattern is arguably one of the most commonly heard design patterns used in daily development.

Definition of the proxy pattern: For some reason an object needs to be provided with a proxy to control access to that object. In this case, 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. It is an object structured pattern.

So you can understand it: for example, if you like to rent a house, you can’t directly with the landlord for a visit to talk with him, then you need a housing intermediary, you tell us what you need him, the landlord also told him that his demand, then he is responsible for as the mouthpiece of intermediate relay you mean, indirect provides you a visit to the landlord!

Part of the

Through the definition and description of the agency model, we can find that it should have three key roles: you, the landlord and the real estate agent. That is:

Abstract role Subject: Declares the common interface of real and proxy objects. The landlord.

Proxy role Proxy: A Proxy object role contains internal references to real objects so that it can operate on real objects. The Proxy object provides the same interface as the real object so that it can replace the real object at any time. At the same time, a proxy object can perform operations on the real object with additional operations attached, which is equivalent to encapsulating the real object. Real estate agent.

Real Role RealSubject: The real object represented by the proxy role is the object we will eventually reference. You are.

Classification of proxy patterns

We often hear the term dynamic proxy, and if there are dynamic proxies, there must be static proxies. Therefore, the proxy mode is mainly divided into dynamic and static proxy design mode. Next, introduce them respectively:

Static agent

A static proxy is one in which a programmer creates a proxy class or a particular tool automatically generates source code and compiles it. The.class file of the proxy class exists before the program runs.

Examples of static proxies:

The interface common to abstract roles, real objects and proxy objects here is the role of the landlord:

package com.jiangxia.ProxyPattern.jingtaiProxy; /** * @author: */ public interface FangDong {// public void sign (); Public void lookHouse (); }Copy the code

The proxy role needs to implement the methods of the abstract role, here is the mediation role:

package com.jiangxia.ProxyPattern.jingtaiProxy; /** * @author: @date: 2021/10/31/10:10 * @description: */ public class ZhongJie implements FangDong{ public FangDong fangDong; public ZhongJie(FangDong fangDong) { this.fangDong = fangDong; } @override public void sign() {system.out.println (); } @override public void lookHouse() {system.out.println (); }}Copy the code

Real Characters, you:

package com.jiangxia.ProxyPattern.jingtaiProxy; /** * @author: @date: 2021/10/31/10:13 * @description: */ public class implements FangDong{@override public void sign() {system.out.println (); ); } @override public void lookHouse() {system.out.println (); ); }}Copy the code

Test code:

/** * @author: @date: 2021/10/31/10:15 * @description: */ public class Test { public static void main(String[] args) { FangDong fangke = new FangKe(); FangDong zhongjie = new ZhongJie(new FangKe()); zhongjie.lookHouse(); zhongjie.sign(); }}Copy the code

The following output is displayed:

A dynamic proxy

Unlike static proxies, the source code for dynamic proxy classes is dynamically generated by the JVM at runtime, based on mechanisms such as reflection, so there are no bytecode files for proxy classes. The relationship between the proxy role and the real role is determined at runtime.

Dynamic proxy is a more advanced proxy pattern, and its typical application is Spring AOP.

Examples of dynamic proxies:

The abstract and real characters that is, the landlord and tenant codes are the same as above. The main differences are the handling of proxy roles and method calls:

The agent code is as follows:

package com.jiangxia.ProxyPattern.Dongtai;

import com.jiangxia.ProxyPattern.jingtaiProxy.FangDong;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

public class proxyHandler  implements InvocationHandler {

         private FangDong userImpl;
         public proxyHandler(FangDong userImpl){
             this.userImpl= userImpl;
         }
         @Override
         public Object invoke(Object proxy, Method method, Object[] args)
                                        throws Throwable {
                   Object object = null;
       //方法开始前做一些事情
       if (method.getName().equals("sign")) {
           //激活调用的方法
           object = method.invoke(userImpl, args);
       }
       //方法结束后做一些事情
       return object;
    }
}
Copy the code

Test code:

package com.jiangxia.ProxyPattern.Dongtai; import com.jiangxia.ProxyPattern.jingtaiProxy.FangDong; import com.jiangxia.ProxyPattern.jingtaiProxy.FangKe; import java.lang.reflect.Proxy; public class Test { public static void main(String[] args) { FangDong fangek =new FangKe(); proxyHandler handler = new proxyHandler(fangek); FangDong zhongjie = (FangDong)Proxy.newProxyInstance (ClassLoader.getSystemClassLoader(), new Class[]{FangDong.class}, handler); zhongjie.sign(); }}Copy the code

Running results:

Advantages of proxy mode

1. The business class only needs to focus on the business logic itself, ensuring the reuse of the business class. This is the common advantage of agency.

2, can coordinate the caller and the called, reduce the coupling degree of the system to a certain extent.

3. Virtual agent can reduce the consumption of system resources, optimize the system and improve the running speed by using a small object to represent a large object.

4. Protection agents can control access to real objects.

5. Remote proxy enables clients to access objects on remote machines, which may have better computing performance and processing speed, and can quickly respond to and process client requests.

Disadvantages of proxy mode

Some types of proxy patterns may slow down the processing of requests due to the addition of proxy objects between the client and the real subject, such as secure proxies.

2. Implementing the proxy pattern requires additional work, and some proxy patterns, such as remote proxy, are more complex to implement.

Application scenarios

When you cannot or do not want to refer to an object directly or it is difficult to access an object, you can access it indirectly through a proxy object. The proxy pattern is used for two purposes: to protect and enhance target objects. After analyzing the structure and characteristics of the proxy pattern, let’s look at the following application scenarios.

1, remote proxy, this method is usually to hide the fact that the target object exists in different address space, convenient client access. For example, when a user applies for some web disk space, a virtual disk is created in the user’s file system. When the user accesses the virtual disk, the user accesses the web disk space.

2. Virtual proxy, which is usually used when the target object to be created is expensive. For example, it takes a long time to download a large image, which cannot be completed in a short time due to some complicated calculation. In this case, the real object can be replaced with a small proportion of virtual agents to eliminate the user’s feeling of slow server.

3. Secure proxy, which is usually used to control access to real objects by different types of clients.

4, intelligence guidance, mainly used to call the target object, the agent to attach some additional processing functions. For example, add the ability to count the number of references to a real object so that when the object is not referenced, it can be released automatically.

5. Lazy loading refers to delaying the loading of the target in order to improve the system performance. Hibernate, for example, has lazy loading of attributes and lazy loading of associated tables.

AOP in Spring uses dynamic proxies

Related to recommend

Learning Design Patterns from Scratch part 1: What are Design Patterns

Learning design Patterns from scratch (PART 2) : Singleton patterns

Learning design Patterns from Scratch (3)

Learning design Patterns from Scratch (4) : Factory Pattern

Learning Design Pattern from Scratch (5) : Builder Pattern

Learning design Patterns from Scratch (6) : Adapter Pattern