The proxy mode of the Java design pattern--the work of the broker

foreword

This article mainly talks about the agent mode . The easy-to-understand cases are used in the article, so that you can better learn the knowledge points of this chapter and understand the principles, so that you can do it wisely.

1. What is the proxy mode

The proxy mode is one of the structural modes among the 23 design modes . Its core is to complete the access of other objects through the proxy class, reduce the coupling degree between the visitor and the visitor, and enhance the function.

2. Agency model in life

1. Broker

Every artist has his own agent to help him handle work matters, such as helping the artist pick up jobs, business negotiations, promotional packaging, etc. If we want to contact an artist, it is mainly done through the agent, and The broker is similar to the proxy pattern in the design pattern.

2. Real estate agency

Now many young people work in big cities and live in rented houses. If you buy a house or rent a house now, do you go through a real estate agency? Anyway, you find a house through a real estate agency, and the real estate agency is responsible for helping the owner sell or rent out the house. Yes, through the real estate agency, we don’t need to contact the owner to obtain the housing information for each house, which greatly improves the efficiency of our house selection, and the real estate agency is similar to the agency model in the design model.

3. Matchmaking

Now there are many matchmaking companies or various APPs to help you expand your social scope, meet more people, and increase your love and marriage rates. The matchmaking company or various dating apps are similar to the agency model in the design model.

3. Realization of proxy mode

There are two proxy modes, one is static proxy and the other is dynamic proxy

1. Static proxy

Next, let's take actors and agents as examples, and realize it through static agents. First create an interface and proxy object class actor class and static proxy class broker class

package com.qianfeng.ran;

/*
 * @author:江帅
 *      接口
 *          人类接口
 */
public interface Human {
    
    
    void behavior();
}



/*
 * @author:江帅
 *      被代理对象类
 *              演员类
 */
class Actor implements Human{
    
    
    @Override
    public void behavior() {
    
    
        System.out.println("某某明星进行拍戏");
    }
}



/*
 * @author:江帅
 *      静态代理类
 *          经纪人
 */
class Broker implements Human{
    
    
    private Human human;
    //获取具体的明星对象
    public Broker(Human human){
    
    
        this.human = human;
    }
    @Override
    public void behavior() {
    
    
        System.out.println("接商演");
        System.out.println("安排行程");
        human.behavior();
        System.out.println("后续工作进行");
    }
}

Then create a client to use the proxy mode to contact the actor through the agent to let the actor film and enhance the function

package com.qianfeng.ran;

/*
 * @author:江帅
 *          客户端
 */
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        //创建明星对象
        Actor actor = new Actor();

        //创建经纪人对象并传递明星对象
        Broker broker = new Broker(actor);
        //执行结果:
        //接商演
        //安排行程
        //某某明星进行拍戏
        //后续工作进行
        broker.behavior();
    }
}

2. Dynamic proxy

Next, let's take the real estate agency as an example and use dynamic agents to achieve it. First create the proxy interface human interface and the proxy object class user class

package com.qianfeng.ran;

/*
 * @author:江帅
 *          接口
 *              人类接口
 */
public interface Human {
    
    
    void behavior();
}



/*
 * @author:江帅
 *          被代理对象类
 *              用户
 */
public class User implements Human{
    
    
    @Override
    public void behavior() {
    
    
        System.out.println("租房");
    }
}

Create a dynamic proxy real estate agency class

package com.qianfeng.ran;
/*
 * @author:江帅
 *         动态代理类
 *              房产中介
 */
public class DynamicProxy implements InvocationHandler {
    
    
    //需要被代理的对象
    private Object obj;

    public Object newInstance(Object obj){
    
    
        this.obj = obj;
        /**
         *  第一个参数为被代理对象的类加载器
         *  第二个参数为被代理对象的接口
         *  第三个此参数为当前对象
         */
        return Proxy.newProxyInstance(obj.getClass().getClassLoader()
                ,obj.getClass().getInterfaces(),
                this);
    }

    /**
     *  调用被代理对象的方法都会经过该方法
     * @param proxy 代理对象的引用
     * @param method 被调用的方法对象
     * @param args  被调用方法的参数数组
     * @return		原方法的返回值
     * @throws Throwable
     */
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
    
    
        start();
        //调用被代理对象的方法
        Object respBean = method.invoke(obj, args);
        commit();
        return respBean;
    }

    public void start(){
    
    
        System.out.println("带客户看房子");
    }

    public void commit(){
    
    
        System.out.println("与客户签署合同");
    }
}

Finally, the dynamic proxy realizes the enhancement of users' behavior of looking for houses through real estate intermediaries

package com.qianfeng.ran;

/*
 * @author:江帅
 *      客户端
 */
public class Demo {
    
    
    public static void main(String[] args) {
    
    
        //创建房产中介            --  代理对象类
        DynamicProxy proxy = new DynamicProxy();

        //通过房产中介找房子     --   调用代理对象的方法并传递被代理对象,实现增强
        Human human = (Human) proxy.newInstance(new User());
        //执行结果:
        //带客户看房子
        //租房
        //与客户签署合同
        human.behavior();
    }
}

4. Supporting video

If you are not used to reading technical articles, or do not have a good understanding of the technical concepts in the article, you can take a look at the video tutorials we have selected for you.

Qianfeng Education Java Tutorial Video Detailed Explanation of Java Design Patterns, 12 Latest Java Design Patterns in the Whole Network (Illustration + Source Code Analysis + Actual Combat)

5. Summary

There are two types of agents in the agent mode: static agents and dynamic agents

The implementation of static proxy will lead to the redundancy of proxy class, every time a proxied object is added, a proxy class needs to be added. Just like a one-on-one celebrity agent, every additional star needs an additional agent.

The implementation of dynamic proxy reduces the redundancy of the proxy class. Only one dynamic proxy class is needed, but each method of the proxied object will be enhanced. Just like a real estate agency, there is no need for an additional intermediary to serve each multiple customers. A real estate agency can serve multiple users, but each user gets the same real estate agency service.

In the next chapter, we will take you to learn the relationship between computers and games (the bridge mode of design mode)

Guess you like

Origin blog.csdn.net/GUDUzhongliang/article/details/131300705