Application scenarios

The main purposes of using the proxy pattern are:

  1. Protecting target objects

  2. Enhance target object

Static agent

Public interface IOrderSerivce() {int createOrder(Order Order); Public class OrderService Implements IOrderService {int createOrder(Order Order) {// Public Class OrderServiceStaticProxy implements IOrderService {private IOrderSerivce orderService; public OrderServiceStaticProxy(IOrderService orderService) { this.orderService = orderService; } public int createOrdr(Order order) { // do something orderService.create(order); IOrderService orderService = new OrderServiceStaticProxy(new orderService ())); orderService.create(order);Copy the code

A dynamic proxy

public class MyProxy Implements InvationHandler {
	private Object target;
    
    public Object getInstance(Object object) throws Exception {
    	this.target = target;
        Class<?> clazz = target.getClass();
        return Proxy.getProxyInstance(clazz.getClassLoader(), clazz.getInterface(), this);
    }
    
    public Object invoke(Object proxy, Method method, Object[] args) throws Exception {
    	before();
        Object obj = method.invoke(this.target, args);
        after();
        return obj;
    }
    
}
Copy the code