Skip to content

已阅读

0%

Java静态代理

Java Proxy

Java静态代理

标签:
Java
发布于 2023年8月31日
更新于 2023年8月31日

Java静态代理是一种实现代理设计模式的方式,它允许你为一个类创建一个代理类,这个代理类可以拦截并增强原始类的方法调用。

Java静态代理的特点是:

  • 代理类和被代理类在编译期间就确定下来了,不利于程序的扩展。
  • 在代理对象和真实对象之间存在固定的绑定关系,如果要更换代理对象,必须修改源代码,不符合开闭原则。
  • 可以在不修改目标对象的前提下,对目标对象进行功能扩展。

Java静态代理的缺陷包括:

  • 静态代理需要为每一个被代理类创建一个代理类,当被代理类较多时,会导致类的数量急剧增加,不利于代码的维护。
  • 静态代理只能代理特定的接口或类,如果需要代理的接口或类较多,就需要创建相应数量的代理类,增加了开发工作量。
  • 静态代理的功能扩展需要修改源代码,不符合开闭原则,对原有代码的侵入性较大。
  • 静态代理只能在编译期间确定代理关系,无法动态地在运行时切换代理对象。

示例:

定义一个接口

java
public interface Animal {
    void type();
}

实现该接口

java
public class Cat implements Animal {

    @Override
    public void type(){
        System.out.println("Type is cat");        
    }
}

创建代理类

java
public class AnimalProxy implements Animal {

    private final Animal animal;
    
    public AnimalProxy(Animal animal){
        this.animal = animal;
    }

    @Override
    public void type(){
        System.out.println("Before method call"); 
        animal.type();
        System.out.println("After method call");          
    }
}

使用

java
public class Main {

    public static void main(String[] args) throws Exception {  
        Animal animal = new Cat();
        AnimalProxy proxy = new AnimalProxy(animal);
        proxy.type();  
    }

}

输出:

text
Before method call
Type is cat
After method call

Last updated: