java中的静态代理

发现python中的元类和java中的动态代理很像,打算写两篇随笔总结一下java中的代理机制

代理模式直白的说就是增强某一个类的功能,在实际开发中,我们大多数时候出于维护旧代码或者解耦的原因,不能去改动原来的类,这时候代理类就派上用场了

那么面对对象的设计思路中,增强一个类的除了继承外,我们还可以新建一个代理类实现被代理类的接口,在代理类中调用被代理类的方法,看图可能更直观一点

下面直接上代码

/**
 接口定义
 */
public interface TargetInterface {
    void say();
    void eat();
}

/**
 被代理类
 */
public class ProxyTarget implements TargetInterface {
    public void say(){
        System.out.println(this);
    }

    @Override
    public void eat() {
        System.out.println("我是被代理对象eat");
    }

    @Override
    public String toString() {
        return "我是要被代理的类";
    }
    public static void main(String[] args) {
        new ProxyTarget().say();
    }
}

/**
 *代理类
 */
public class TestProxy implements TargetInterface {

private TargetInterface targetInterface;

public TestProxy(TargetInterface targetInterface) {
this.targetInterface = targetInterface;
}

public void say() {
targetInterface.say();
System.out.println("我变强了");
}

@Override
public void eat() {
targetInterface.say();
System.out.println("我变强了");
}

public static void main(String[] args) {//测试代码


TargetInterface interfa = new ProxyTarget();
TestProxy testProxy = new TestProxy(interfa);
testProxy.eat();
}
}

输出

我是要被代理的类
我变强了

这样在原来类不变的情况下,我们增强了原来的类,但静态代理有几个弊端,如果我们要实现的类比较多,每一个接口都要写一个代理类,增加负担,为了解决这个问题,引入动态代理的机制,动态生成代理类,下一篇随笔介绍

原文地址:https://www.cnblogs.com/qunincey/p/9397899.html