

新闻资讯
行业动态代理模式重在控制访问,装饰模式重在动态增强功能;代理强调替代性与单一控制点,装饰强调叠加性与正交增强,二者目的、场景及UML依赖关系均不同。
代理模式和装饰模式在 Java 中都属于结构型设计模式,表面看都用“包装”对象的方式扩展行为,但目的和使用场景截然不同:代理模式重在**控制访问**(比如权限校验、延迟加载、远程调用),装饰模式重在**动态增强功能**(比如给输入流加缓冲、给组件加边框)。
代理类与被代理类实现同一接口,代理类持有真实对象引用,在调用前后可插入逻辑,但不改变原有接口语义。常见错误是把代理写成“功能叠加器”,结果混淆了职责。
Proxy 类必须和 RealSubject 实现同一个 Subject 接口,否则无法透明替换java.lang.reflect.Proxy)则通过 InvocationHandler 统一拦截final 类或方法无法被 JDK 代理public interface Service {
void execute();
}
public class RealService implements Service {
public void execute() { System.out.println("real work"); }
}
public class LoggingProxy implements Service {
private final Service target;
public LoggingProxy(Service target) { this.target = target; }
public void execute() {
System.out.println("before");
target.execute();
System.out.println("after");
}
}
装饰类与被装饰类实现同一接口,且持有被装饰对象引用,通过构造函数传入——这是它和代理最直观的代码相似点;但装饰模式的意图是让多个装饰器像俄罗斯套娃一样自由堆叠,每层只专注单一职责增强。
BufferedInputStream 装饰 FileInputStream,而它本身又可被 DataInputStream 装饰——顺序影响行为(如先缓冲再读数据,不能反过来)public interface Coffee {
String getDescription();
double getCost();
}
public class SimpleCoffee implements Coffee {
public String getDescription() { return "Simple coffee"; }
public double getCost() { return 2.0; }
}
public class Milk implements Coffee {
private final Coffee coffee;
public Milk(Coffee coffee) { this.coffee = coffee; }
public String getDescription() { return coffee.getDescription() + ", milk"; }
public double getCost() { return coffee.getCost(
) + 0.5; }
}
一个典型误用:用装饰器做权限检查。这看似可行,但破坏了装饰的“正交增强”原则——权限不是业务功能的自然延伸,而是横切关注点,该由代理或 AOP 承担。反之,若用代理去实现多层日志+压缩+加密,就违背了代理“单一控制点”的定位,代码会迅速僵化。
真正难的是在需求模糊时判断:这个“包装”是为了管控访问,还是为了丰富能力?一旦方向错了,后续每加一层都会让维护成本翻倍。