“This is the 25th day of my participation in the Gwen Challenge in November. See details: The Last Gwen Challenge in 2021”

This is the fourth article on design patterns, in which all the design patterns I will encounter are summarized one by one. I will write down my thoughts on each design pattern and how we can flexibly apply these design patterns in practical work. Welcome your attention. In this article, we will talk about the most important agency model.

A brief introduction to the proxy pattern

The agent mode is to create an agent for the object, which is just like the intermediary in our life. We will entrust the matter of buying a house to the intermediary, and the intermediary can help us realize the matter of buying a house, and they will complete the operation of looking for customers and collecting intermediary fees in the process of buying a house.

Class diagram for proxy mode

The proxy model is further subdivided into two types:

  • Static agent

    Build a proxy object that can call corresponding methods from real objects and do other things besides implementing real object methods.

  • A dynamic proxy

    Dynamic proxy objects do not need to be created manually, but are created dynamically based on real objects.

    Java dynamic proxies come in two main forms

    • JDK dynamic proxy
    • Cglib dynamic proxy

The concrete realization idea of proxy mode

  • Static agent

    • Creating abstract Objects
    • Creating a real object
    • Creating a proxy object
  • A dynamic proxy

    • Create an interface (you don’t have to)
    • Creating the target Object
    • Dynamic proxies are implemented using JDK for interfaces created, and Cglib for uncreated interfaces

The concrete implementation scheme of proxy mode

  • Static agent

    Public interface AbstractSubject {void request(); Public class RealSubject implements AbstractSubject {public void request(){}} public class ProxySubject implements AbstractSubject { private RealSubject realSubject; public ProxySubject(RealSubject realSubject){ this.realSubject = realSubject; } public void request(){realsubject.request (); // Other operations}}Copy the code
  • A dynamic proxy

    JDK dynamic proxy

    The JDK simply implements the Proxy using the newProxyInstance method of java.lang.reflect.Proxy

    Public class ProxyFactory{private Object target; public ProxyFactory(Object target){ this.target=target; } public Object getProxyInstance(){return proxy.newProxyInstance () target.getClass().getClassLoader(), target.getClass().getInterfaces(), new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {// Other operations // Execute the method of the target Object Object returnValue = method.invoke(target, args); Return returnValue; }}); }}Copy the code

    Cglib dynamic proxies implement proxies by creating subclasses

    Public class ProxyFactory implements MethodInterceptor{// Private Object target; public ProxyFactory(Object target) { this.target = target; } public Object getProxyInstance(){// 1. Enhancer en = new Enhancer(); En.setsuperclass (target.getClass())); // 3. Set the en.setcallback (this) function; // 4. Create subclass (proxy object) return en.create(); } @Override public Object intercept(Object obj, Method method, Object[] args, Object returnValue = method.invoke(target, args); Return returnValue; }}Copy the code

Advantages and disadvantages of the proxy model

advantages

  • Protect the target object.
  • Through the proxy object, to enhance the target object, we only need to modify the proxy class without modifying the delegate class, in line with the open and closed principle of code design.

disadvantages

  • The call complexity increases, which may affect the execution efficiency
  • Problems may occur on proxy objects, which is not conducive to troubleshooting

Application scenarios of the proxy mode

  1. In some cases, a client class may not want or be able to directly reference a delegate object, while a proxy class object may act as an intermediary between the client class and the delegate object, characterized by the fact that the proxy class and the delegate class implement the same interface.
  2. The proxy class can pre-process messages for the delegate class, filter messages, forward messages to the delegate class, and process the returned results afterwards.
  3. The proxy class itself does not actually implement the service, but rather provides specific services by calling the related methods of the delegate class. The real business functions are still implemented by delegate classes, but some common services can be added before and after the implementation of business functions.

For example, adding caching and logging to the project can be done through the proxy class without modifying the encapsulated delegate class.

Spring’S AOP is an encapsulation of dynamic proxies, and some of the functions we use AOP to implement are actually developed using proxy patterns.

Summary of proxy Model

Proxy mode is arguably one of the most practical design patterns, especially in solving some general, excellent results, such as log, we need to record in and out, and access is which method, using dynamic proxy, can greatly reduce the amount of our code, originally need each method to write again, with the dynamic proxy, We just need to write this repetitive code in the proxy class so that we can implement section-oriented development.