头图
The original text was first published on the WeChat public account: jzman-blog, welcome to follow and exchange!

Today, let’s take a look at what is the proxy design pattern. As the name suggests, the proxy is to do something on behalf of someone through an intermediary. Corresponding to our program is to control the access of a specific object and a method through the proxy object. Some additional processing can be done before and after.

  1. Conceptual understanding
  2. Static proxy
  3. Dynamic proxy

Conceptual understanding

  • abstract role : used to define methods shared by real and agent roles.
  • real role : specific business logic to be implemented by the real role for the agent role to call.
  • proxy role : used to proxy the real role, which can perform additional processing before and after the specific logic of the real role.

Then the significance of the agent is that the specific business method of the real role is called when the specific business logic is needed, that is, the processing that is not related to the specific business logic of the real role is processed in the agent class.

Static proxy

Let's take a look at the code implementation of the static proxy first, and define the business logic shared by the abstract role declaration, as follows:

/**
 * 抽象角色
 * @author jzman
 */
public interface IBusiness {
    /**
     * 购物
     */
    void buy();
}

Then, create a real role and complete the specific business logic, as follows:

/**
 * 真实角色
 * @author jzman
 */
public class RealRole implements IBusiness{
    @Override
    public void buy() {
        System.out.println("我要买东西");
    }
}

Then, the agent role is created, and the business logic method of the real role must be called when performing the specific business logic, as follows:

/**
 * 代理角色
 * @author jzman
 */
public class ProxyRole implements IBusiness{
    
    private IBusiness mRealRole;
    
    public ProxyRole(IBusiness realRole) {
        this.mRealRole = realRole;
    }

    @Override
    public void buy() {
        //购买之前的额外评估
        System.out.println("购买之前的额外评估...");
        //具体的业务逻辑
        mRealRole.buy();
        //购买之后的满意度调查
        System.out.println("购买之后的满意度调查...");
    }
}

Finally, use the related static proxy class you just created, as follows:

/**
 * 测试静态代理
 * @author jzman
 */
public class StaticClient {
    public static void main(String[] args) {
        //创建真实角色
        IBusiness realRole = new RealRole();
        //创建代理角色
        IBusiness proxyRole = new ProxyRole(realRole);
        //代购帮你买东西
        proxyRole.buy();
    }
}

The test results are as follows:

购买之前的额外评估...
我要买东西
购买之后的满意度调查...

In this case, the Daigou agent not only helped us buy things, but also did additional processing before and after the purchase. Isn’t it very flexible?

Dynamic proxy

I understand the static proxy above, so what is the difference between a dynamic proxy and a static proxy? In fact, the main difference between a static proxy and a dynamic proxy is that the static proxy needs to generate proxy classes by itself, and the dynamic proxy automatically generates proxy classes during the code running process, then The dynamic proxy is implemented as follows. First, let's take a look at the two key classes or interfaces that implement dynamic proxy that comes with the Java JDK. The details are as follows:

//用于动态生成代理类及其对象
java.lang.reflect.Proxy
//代理角色的调用处理程序需要实现的接口
//用于约束调用者的实现,抽象角色调用方法的时候会被该接口的invoke方法调用
java.lang.reflect.InvocationHandler

Let's implement the dynamic proxy that comes with the Java JDK. First, the abstract role and the real role are the same as the static proxy above. I won't go into details here. The call handler for creating a proxy role is as follows:

/**
 * 代理角色的调用处理程序
 * @author jzman
 */
public class BusinessHandler implements InvocationHandler{

    private IBusiness mRealRole;
    
    public BusinessHandler(IBusiness mRealRole) {
        super();
        this.mRealRole = mRealRole;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //购买之前的额外评估
        System.out.println("购买之前的额外评估...");
        
        //真实角色具体的业务逻辑
        method.invoke(mRealRole, args);
        
        //购买之后的满意度调查
        System.out.println("购买之后的满意度调查...");
        
        return null;
    }
}

Use the static method newProxyInstance() of Proxy to generate proxy objects, as follows:

/**
 * 测试JDK自带的动态代理
 * @author jzman
 *
 */
public class DynamicProxyClient {
    public static void main(String[] args) {
        //创建真实角色
        IBusiness mRealRole = new RealRole();
        
        //创建处理器接口
        InvocationHandler handler = new BusinessHandler(mRealRole);
        /**
         * 获取代理角色对应的代理对象
         * newProxyInstance参数(类加载器,自动生成的代理类实现的接口,代理对象的调用处理程序)
         */
        IBusiness proxy = (IBusiness) Proxy.newProxyInstance(handler.getClass().getClassLoader(), mRealRole.getClass().getInterfaces(), handler);
        
        //代理角色帮你买东西
        proxy.buy();
    }
}

The execution result of the above code is as follows:

购买之前的额外评估...
我要买东西
购买之后的满意度调查...

Learning static agents is helpful to the learning of dynamic agents. The main difference between the two is that dynamic agents do not need to write agent classes, and their corresponding agent classes will be dynamically generated during code running. Of course, the generated agent classes also implement abstract role correspondence. At the same time, an InvocationHandler that creates a proxy role will also take over the specific business logic. That's it for static proxy and dynamic proxy. You can choose to follow your personal WeChat public get the latest updates, exchange and learn together!

1.png


躬行之
18 声望5 粉丝