【java基础】静态代理和动态代理

代理模式

代理是基本的设计模式之一,提供额外的或不同的操作,代理通常充当中间人的角色,如果用“租房子”来打比方,代理则是中介

静态代理

package com.oxygen.proxy;

/**
 * @author Oxygen
 * @date 2018年10月10日
 */
public interface TargetInterface { // 接口
    void method1(); /* public abstract */
    void method2(String arg);
}
package com.oxygen.proxy;

/**
 * @author Oxygen
 * @date 2018年10月10日
 */
public class SimpleProxyDemo {
    public static void consumer(TargetInterface iface) {
        iface.method1();
        iface.method2("bonobo");
    }

    public static void main(String[] args) {
        consumer(new Target());
        consumer(new SimpleProxy(new Target()));
    }
}

class Target implements TargetInterface { // 目标对象

    @Override
    public void method1() { 
        System.out.println("method1 run ");
    }

    @Override
    public void method2(String arg) {
        System.out.println("method2 run" + arg);
    }
}

class SimpleProxy implements TargetInterface { // 静态代理对象
    private TargetInterface proxied; //

    public SimpleProxy(TargetInterface proxied) {
        super();
        this.proxied = proxied;
    }

    @Override
    public void method1() {
        System.out.println("=====before method1===== "); // 代理对象增强方法的代码
        proxied.method1();
        System.out.println("=====after method1===== "); // 代理对象增强方法的代码
    }

    @Override
    public void method2(String arg) {
        System.out.println("=====before method2===== "); // 代理对象增强方法的代码
        proxied.method2(arg);
        System.out.println("=====after method2===== "); // 代理对象增强方法的代码
    }
}
output:
method1 run method2 runbonobo
=====before method1===== method1 run =====after method1===== =====before method2===== method2 runbonobo =====after method2=====

猜你喜欢

转载自www.cnblogs.com/oxygenG/p/9765542.html