Interviewer: You should learn more about the proxy mode!

Proxy mode

Today we will learn the twelfth of the 23 design patterns-the proxy pattern. The proxy mode is to provide a proxy for an object, and the proxy object controls the reference to the original object. It makes it impossible for clients to communicate directly with the real target object. The proxy object is the representative of the target object, and other operations that need to deal with this target object are all negotiating with this proxy object.

concept:

The proxy mode is that for some reason it is necessary to provide an object with a proxy to control access to the object. At this time, the access object is not suitable or cannot directly refer to the target object, and the proxy object will act as an intermediary between the access object and the target object.

Features:

advantage:

  • The proxy mode plays an intermediary role between the client and the target object and protects the target object;
  • The proxy object can extend the functionality of the target object;
  • The proxy mode can separate the client from the target object, reducing the coupling of the system to a certain extent.

shortcoming:

  • Adding a proxy object between the client and the target object will slow down the request processing speed;
  • Increased system complexity.
code:

1. Static proxy

目标接口

package cn.ppdxzz.proxy.staticproxy;

/**
 * description:目标接口
 * @author: PeiChen JavaAnything
 */
public interface ITeacherDao {
    
    
    /**
     * 教师授课的方法
     */
    void teach();
}

目标对象(被代理对象)

package cn.ppdxzz.proxy.staticproxy;

/**
 * description:目标对象(被代理对象)
 * @author: PeiChen JavaAnything
 */
public class TeacherDao implements ITeacherDao {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("教师授课中...");
    }
}

代理对象

package cn.ppdxzz.proxy.staticproxy;

/**
 * description:代理对象
 * @author: PeiChen JavaAnything
 */
public class TeacherDaoProxy implements ITeacherDao {
    
    
    /**
     * 目标对象,通过接口来聚合
     */
    private final ITeacherDao targetObject;

    public TeacherDaoProxy(ITeacherDao targetObject) {
    
    
        this.targetObject = targetObject;
    }

    /**
     * 具体代理操作的实现
     */
    @Override
    public void teach() {
    
    
        System.out.println("开始代理某些操作...");
        targetObject.teach();
        System.out.println("代理操作完成");
    }
}

静态代理客户端

package cn.ppdxzz.proxy.staticproxy;

/**
 * description:静态代理客户端
 * @author: PeiChen JavaAnything
 */
public class Client {
    
    
    public static void main(String[] args) {
    
    
        //1. 创建目标对象(被代理对象)
        TeacherDao targetObject = new TeacherDao();
        //2. 创建代理对象,把被代理对象传给代理对象
        TeacherDaoProxy proxy = new TeacherDaoProxy(targetObject);
        //3. 通过代理对象,去调用被代理对象的方法,执行的是代理对象的方法,代理对象再去调用目标对象的方法
        proxy.teach();
    }
}

operation result:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-eTEgcLkh-1591153932251)(D:\cloudnote\images\image-20200426101603467.png)]

Advantages and disadvantages of static proxy:

advantage:

  • On the premise of not modifying the function of the target object, the target function can be extended through the proxy object.

shortcoming:

  • Because the proxy object needs to implement the same interface as the target object, there will be many proxy classes.

  • Once the method is added to the interface, both the target object and the proxy object must be maintained.

2. Dynamic proxy

目标接口

package cn.ppdxzz.proxy.dynamicproxy;

/**
 * description:目标接口
 * @author: PeiChen JavaAnything
 */
public interface ITeacherDao {
    
    
    /**
     * 授课
     */
    void teach();

    /**
     * 问好
     * @param name 姓名
     */
    void sayHello(String name);
}

目标对象(被代理对象)

package cn.ppdxzz.proxy.dynamicproxy;

/**
 * description:目标对象(被代理对象)
 * @author: PeiChen JavaAnything
 */
public class TeacherDao implements ITeacherDao {
    
    
    @Override
    public void teach() {
    
    
        System.out.println("教师授课中...");
    }

    @Override
    public void sayHello(String name) {
    
    
        System.out.println("hello" + name);
    }
}

代理对象

package cn.ppdxzz.proxy.dynamicproxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * description:代理对象
 * @author: PeiChen JavaAnything
 */
public class ProxyFactory {
    
    
    /**
     * 维护一个Object类型的目标对象
     */
    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 {
    
    
                System.out.println("JDK代理开始...");
                //反射机制调用目标对象的方法
                Object returnVal = method.invoke(target, args);
                System.out.println("JDK代理提交");
                return returnVal;
            }
        });

    }
}

动态代理客户端

package cn.ppdxzz.proxy.dynamicproxy;

/**
 * description:动态代理客户端
 * @author: PeiChen JavaAnything
 */
public class Client {
    
    
    public static void main(String[] args) {
    
    
        //创建目标对象
        ITeacherDao target = new TeacherDao();
        //创建代理对象
        ITeacherDao proxyInstance = (ITeacherDao)new ProxyFactory(target).getProxyInstance();
        proxyInstance.teach();
        proxyInstance.sayHello("小万");
    }

}

operation result:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-ojGGKIyd-1591153932255)(D:\cloudnote\images\image-20200426180534382.png)]

The proxy mode is very common in real life. For example, the intranet penetrates the firewall through a proxy to achieve access to the public network, which uses the proxy mode.

Guess you like

Origin blog.csdn.net/active_pig/article/details/106520088