This is the ninth day of my participation in the First Challenge 2022

The proxy pattern

concept

Proxy Pattern refers to the function that one class represents another class, provides a Proxy for other objects, and the Proxy object controls the reference to the original object.

In general, it is to set up an intermediate proxy to control the access to the original object in order to enhance the function of the original object and simplify the access mode. In terms of class loading, the proxy pattern is a structural pattern.

The proxy mode is mainly used in cases where one object does not fit or cannot directly call another object, and the proxy object in the proxy mode acts as a mediation connection between the client and the user. For example, in real life, the agent between rental and landlord is the real estate agent, and the agent between Taobao merchants and users is the express delivery point.

Implementation principle of proxy mode

  • Generic class diagram for the proxy pattern

As can be seen from the figure above, ISubject is an abstract interface, RealSubject is the implementation method class, and TikTokProxy is the proxy object of RealSubject. MainTest directly initializes TikTokProxy. You can call the Request method in the RealSubject.

The proxy mode can add and enhance some functions by extending the proxy class without modifying the proxy object. It is important to note that the proxied and proxied classes should implement an interface or inherit from a class in common.

  • Proxy mode role

    • Abstract Topic roles (ISubject): Declare common interface methods for topics and proxy objects. This class can be an interface class or an abstract class

    • Proxy: mainly refers to the Proxy class, which internally defines the reference of the Proxy class and fully has the Proxy right of the Proxy class. Code enhancement can be achieved in the Proxy topic.

    • RealSubject: real principal roles, mainly proxyed classes, which define the real objects represented by the agent and are the real logical business objects responsible for executing the system

Application scenarios of proxy mode

There are many application scenarios in life, such as rental agents, scalpers, express delivery, etc., which are the actual embodiment of the agency mode in reality. When you cannot or do not want to refer to an object directly, or when accessing an object is difficult, you can access it through a proxy object. The main advantages of using proxy mode are: 1, protect the target object (proxied object), 2, enhance the target object

There’s a lot of it in the code, for example

  • How is Mybatis Mapper generated

  • What is Alibaba Seata’s DataSourceProxy

  • How does DruidDataSource’s monitor chain act as a proxy

  • How does Spring delegate

Static agent

Static proxies generally require the proxy object to implement the same interface as the target object

Code implementation

  • Interface class (ISubject)
public interface ISubject {
    void request(a);
}
Copy the code
  • Target Object (RealSubject)
public class RealSubject implements ISubject {
    @Override
    public void request(a) {
        System.out.println("People, request......"); }}Copy the code
  • TikTokProxy
public class TikTokProxy implements ISubject {
    private ISubject subject;

    public TikTokProxy(ISubject subject) {
        this.subject = subject;
    }

    @Override
    public void request(a) {
        before();
        subject.request();
        after();
    }
    private void after(a) {
        System.out.println("After strengthening");
    }
    private void before(a) {
        System.out.println("Before"); }}Copy the code

You can see from the above code. TikTokProxy references the target object ISubject and overrides the Request method with method enhancements in it.

Advantages of static proxies

  • The proxy class acts as an intermediary between the client and the proxied class to protect the proxied class

  • The coupling degree of the system is reduced by decoupling the proxy class and the principal class through the interface

Disadvantages of static proxies

  • Code redundancy. There are too many proxy classes because the proxy object implements the same interface as the target object.

  • The code is not easy to maintain. Once the interface adds methods, both the target object and the proxy object are modified.

A dynamic proxy

Dynamic proxy makes use of JDK API to dynamically build proxy objects in memory, so as to realize the proxy function of target objects. Dynamic proxies are also known as JDK proxies or interface proxies.

A dynamic proxy object does not need to implement an interface object, but the proxied object must be guaranteed to implement the interface

Code implementation

  • Interface class
public interface SellTikTok {
    void sell(a);
}
Copy the code
public interface ManTikTok {
    void tikTok(a);
}
Copy the code
  • The target class
public class TikTok implements ManTikTok.SellTikTok {
    @Override
    public void tikTok(a) {
        System.out.println("tikTok....");
    }

    @Override
    public void sell(a) {
        System.out.println("sell...."); }}Copy the code
  • JDK proxy object
public class JdkTikTokProxy<T> implements InvocationHandler {

    private T target;
    public JdkTikTokProxy(T target) {
        this.target = target;
    }
    public static <T> T getProxy(T t) {
        Object o = Proxy.newProxyInstance(t.getClass().getClassLoader()
                , t.getClass().getInterfaces()
                , new JdkTikTokProxy(t));
        return (T) o;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("Methods that actually execute the proxied object");
        Object invoke = method.invoke(target, args);
        System.out.println("Return value:" + invoke);
        return null; }}Copy the code

Pass the proxied object into JdkTikTokProx and the JdkTikTokProx invoke method to obtain the real proxy of the proxied object.

Advantages of dynamic proxies

  • The proxy class is automatically generated by reflection while the program is running, without us writing the proxy class code manually, simplifying the programming work

  • A single dynamic proxy class invoke can proxy multiple proxied classes. There is no need to change the content of the dynamic proxy class

Disadvantages of dynamic proxies

  • Dynamic proxies can only proxy classes that implement interfaces, not classes that implement abstract classes

  • It is inefficient and inefficient to call methods of proxied classes through reflection

The difference between static and dynamic proxies

  • A static proxy can only be manually added. If new methods are added to the proxy class, the proxy class must be added synchronously, violating the open/close principle.

  • Dynamic proxy adopts the method of dynamically generating code at run time, which removes the limitation of extending the proxied class and follows the open and closed principle.

  • If the dynamic proxy wants to extend the enhancement logic of the target class, combined with the policy pattern, it only needs to add the policy class to complete, without modifying the code of the proxy class.

Advantages and disadvantages of the proxy model

advantages

  • The proxy pattern decouples the proxy object from the target object, allowing for appropriate coupling

  • To a certain extent, the coupling of the system is reduced and the expansibility is greatly improved

  • You can protect target objects from intrusion

  • Specific enhancements can be made to the functionality that the target object lacks

disadvantages

  • The proxy pattern adds extra classes to the system

  • Adding a proxy object between the calling class and the called class is inefficient

  • Increase system code complexity