Java中的方法增强

A:在不影响业务情况下,增强一个方法有几种方法呢?

B:3种!

A:哪三种呀?

一、继承类来重写方法;

  1、要可以获取这个类的构造;

class Man{
public void run(){
    System.out.println("跑....");
    }
}

class SuperMan extends Man{
public void run(){
     super.run();
    System.out.println("飞....");
    }
}

二、装饰者模式

  1、包装类要和被包装类实现同一接口;

  2、包装类要获取被包装类的引用;

  

public interface Tenant {
    void rent();
}
public class People implements Tenant {
    public void rent() {
        System.out.println("支付租金");
    }
}
public class PeopleProxy implements Tenant {//实现统一接口
    private People p;

    public PeopleProxy(People p){//获取被包装类的引用
        this.p = p;
    }

    public void rent() {
        System.out.println("我是中介我要先收中介费");
        p.rent();
    }
}

三、动态代理

  1、被增强的对象实现接口即可;

public class ActiveProxy implements InvocationHandler {
    private Object o;

    public ActiveProxy(Object o){
        this.o = o;
    }


    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        Object invoke = method.invoke(this.o, args);
        return invoke;
    }
}
public class Run {
    public static void main(String[] args) {
        //获得要增强实现类的对象
        Tenant p = new People();
        //类加载器
        ClassLoader c = p.getClass().getClassLoader();
        //产生的代理对象的引用
        ActiveProxy handler = new ActiveProxy(p);

        Tenant app = (Tenant) Proxy.newProxyInstance(c,new Class[]{Tenant.class},handler);
        app.rent();
    }
}
原文地址:https://www.cnblogs.com/jiangbaoyabo/p/15176411.html