Agent mode of common design patterns

concept

Proxy Pattern refers to providing a proxy for other objects to control access to this object. This type of design pattern belongs to the structural pattern. The
agency pattern generally contains three roles:

  • Abstract theme role : The main responsibility is to declare the common interface method of the real theme and the agent. This class can be an interface or an abstract class
  • Real theme role : This class is also called the agent class, which defines the real object represented by the agent, and is responsible for the real logical business object of the execution system
  • Agent theme role : also known as the agent class, which holds a reference to the real theme role internally , so it has complete agency power for the real theme role . The client calls the methods of the proxy object and also calls the methods of the proxy object.

classification

The proxy mode is divided into static proxy and dynamic proxy

Static proxy

The bytecode file of the proxy class already exists before the program runs, and the relationship between the proxy class and the delegate class has been confirmed before running

1. Create an abstract theme role class

public interface Payment {
    
    

    String doPqy(String uid);
}

2. Create a real theme character class

public class ThirdChannelPayment implements Payment {
    
    
    public String doPqy(String uid) {
    
    
        System.out.println(uid+"->支付成功");
        return "success";
    }
}

3. Create agent theme role class

public class StaticProxyDemo implements Payment{
    
    
    private Payment pay;

    public StaticProxyDemo(Payment payment) {
    
    
        this.pay=payment;
    }

    public String doPqy(String uid) {
    
    
        System.out.println(uid+"发起支付");
        return pay.doPqy(uid);
    }
}

4. Test class

public class ProxyDemo {
    
    

    public static void main(String[] args) {
    
    
        StaticProxyDemo pay=new StaticProxyDemo(new ThirdChannelPayment());
        System.out.println(pay.doPqy("Tom"));
        }
}

Operation result:
Insert picture description here
UML class diagram is as follows:
Insert picture description here

Disadvantage

The proxy object interface only serves one type of object. If a new method is added, all proxy classes must implement this method, which increases the code maintenance cost

Dynamic proxy

The source code of the dynamic proxy class is dynamically generated through JVM reflection and other mechanisms during the running of the program, and the relationship between the proxy class and the delegate class is confirmed at runtime

JDK dynamic proxy

The premise of using the dynamic proxy generated by jdk is that the target class must have an implemented interface

1. Dynamic proxy class

public class DynamicProxy implements InvocationHandler {
    
    
    private Object target;//被代理的对象

    public Object bind(Object target){
    
    
        this.target=target;
        return Proxy.newProxyInstance(target.getClass().getClassLoader(),target.getClass().getInterfaces(),this);
    }
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        System.out.println("开始");
        Object result=method.invoke(target,args);
        System.out.println("结束");
        return result;
    }
}

2. Test class

public class ProxyDemo {
    
    

    public static void main(String[] args) {
    
    
       //jdk动态代理
        DynamicProxy dp=new DynamicProxy();
        ThirdChannelPayment pay=new ThirdChannelPayment();
        Payment p=(Payment) dp.bind(pay);
        System.out.println(p.doPqy("Jam"));
    }
}

operation result:
Insert picture description here

CGLIB agent

The premise of use is that the target cannot be finalized, because final modified classes cannot be inherited. It is implemented in a way that dynamically generated subclasses inherit the target.

Proxy class

public class CglibProxy implements MethodInterceptor {
    
    

    private  Object target;
    

    public Object getInstance(Object target){
    
    
        this.target=target;
        Enhancer enhancer=new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
    
    
        System.out.println("开始啦");
        Object obj=methodProxy.invokeSuper(o,objects);
        System.out.println("付款结束");
        return obj;
    }
}

test

public class ProxyDemo {
    
    
    public static void main(String[] args) {
    
    
        //cglib代理
        CglibProxy cp=new CglibProxy();
        ThirdChannelPayment tp=new ThirdChannelPayment();
        Payment pay=(Payment) cp.getInstance(tp);
        System.out.println(pay.doPqy("Alia"));
    }
}

operation result:
Insert picture description here

The difference between JDK dynamic proxy and CGLIB proxy

  1. JDK dynamic proxy implements the interface of the proxy object, and CGLIB proxy inherits the proxy object
  2. Both JDK dynamic proxy and CGLIB proxy generate bytecode during runtime. JDK dynamic proxy writes class bytecode directly, and CGLIB proxy uses ASM framework to write class bytecode. CGLIB proxy implementation is more complicated, and the generation of proxy classes is less efficient than JDK dynamic proxy
  3. JDK dynamic proxy calls proxy methods through reflection mechanism, CGLIB proxy calls methods directly through FastClass mechanism, CGLIB proxy execution efficiency is higher
  4. In the Spring framework, when the Bean has an implementation interface, Sring will use JDK dynamic proxy; when the Bean does not implement an interface, Spring will choose CGLIB proxy

The difference between static proxy and dynamic proxy

  1. The static agent can only complete the agent operation manually. If the agent class adds methods, the agent class needs to be added synchronously, which violates the principle of opening and closing
  2. The dynamic proxy adopts the method of dynamically generating code at runtime, cancels the expansion restriction on the proxy class, and follows the opening and closing principle

The principle of opening and closing: a software entity such as class, module and function should be open for extension and closed for modification.

to sum up

If the dynamic agent wants to extend the enhanced logic of the target class, it can be combined with the strategy mode, and it can be completed by adding a new strategy class without modifying the code of the agent class

Advantages of the proxy model:

  1. The proxy mode separates the proxy object from the real called target object, reduces the coupling of the system to a certain extent, and has good scalability
  2. Can play a role in protecting the target
  3. Can enhance the function of the target object

Disadvantages of proxy mode:

  1. The agent mode will increase the number of classes in the system design and increase the complexity of the system
  2. Add a proxy object to the client and target object, causing the request processing speed to slow down

Guess you like

Origin blog.csdn.net/xzw12138/article/details/106640083