Java proxy mode

Definition: Provides a proxy for other objects to control access to this object.

Abstract Theme Interface:

public interface Subject {
    void request();
}

真主题类:

public class RealSubject implements Subject {
    @Override
    public void request() {
        System.out.println("RealSubject..............");
    }
}

静态代理类:


public class Proxy implements Subject {
    Subject subject = null;
    public Proxy(Subject subject) {
        this.subject = subject;
    }

    @Override
    public void request() {
        this.after();
        this.subject.request();
        this.before();
    }

    private void before() {
        System.out.println("before.............");
    }

    private void after() {
        System.out.println("after.............");
    }
}

测试:

public class Example {
    public static void main(String[] args) {
        Subject subject = new RealSubject();
        Proxy proxy = new Proxy(subject);
        proxy.request();
    }
}

动态代理类:

public class DynamicProxy implements InvocationHandler {
    Object target=null;
    public  DynamicProxy(Object proxy){
        this.target=proxy;
    }
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("before...................");
        Object result = method.invoke(target, args);
        System.out.println("after...................");
        return result;
    }
}

测试:

public class DynamicProxyExample {
    public static void main(String[] args) {
        Subject subject = new RealSubject();
        Subject proxySubject = (Subject) Proxy.newProxyInstance(Subject.class.getClassLoader(), new Class[]{Subject.class}, new DynamicProxy(subject));
        proxySubject.request();
    }
}