Java设计模式(十一)--代理模式

114 阅读1分钟

简介

所谓代理模式是指客户端并不直接调用实际的对象,而是通过调用代理对象,来间接的调用实际的对象。

静态代理

静态代理是在编译期间就已经确定好了所需要代理的对象。

抽象类

public interface Base {

    void eat();

}

具体实现类

public class PersonService implements Base {

    public void eat() {
        System.out.println("吃饭");
    }

}

代理类

public class PersonServiceProxy implements Base {

    public Base base;

    public PersonServiceProxy(){
        this.base = new PersonService();
    }

    public void eat() {
        System.out.println("11");
        base.eat();
        System.out.println("22");
    }

}

可以看到在静态代理类中在执行具体方法的之前和之后可以对具体方法进行增强。

测试

public void staticProxy(){
    Base base = new PersonServiceProxy();
    base.eat();
}

我们只需要去创建代理类并调用代理类中的方法,由代理类去调用具体的方法并对方法进行增强。

动态代理

动态代理中所代理的对象不像静态代理一样是固定的,而是在运行期间生成的对象。

代理类

public class PersonServiceProxy implements InvocationHandler {

    private Base base;

    public PersonServiceProxy(Base base){
        this.base = base;
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        System.out.println("11");
        return method.invoke(base,args);
    }
}

代理类实现了InvocationHandler接口并重写了invoke方法,在invoke方法中对代理对象进行了增强。

测试

public void dynamicProxy(){
    PersonServiceProxy personServiceProxy = new PersonServiceProxy(new PersonService());
    Base base = (Base) Proxy.newProxyInstance(personServiceProxy.getClass().getClassLoader(),
            new Class[]{Base.class}, personServiceProxy);
    base.eat();
}