在Java中,适配器模式与装饰器模式有何不同?请通过代码示例说明两者的应用场景。
在 Java 中,适配器模式和装饰器模式是两种常见的设计模式,它们虽然都涉及对类的封装,但解决的问题和适用场景完全不同。以下是它们的区别和代码示例:
适配器模式
适配器模式(Adapter Pattern)用于将不兼容的接口转换为目标接口,使得原本无法一起工作的类能够协同工作。适配器模式主要解决接口不匹配的问题,通常分为类适配器和对象适配器两种形式。
应用场景: 当一个类的功能需要被其他系统使用,但接口不匹配时,可以使用适配器模式。例如,旧系统的接口需要适配到新系统的接口。
示例代码:
// 目标接口(新系统需要的接口)
interface Target {
void request();
}
// 需要被适配的类(旧系统的接口)
class Adaptee {
public void specificRequest() {
System.out.println("Adaptee specificRequest");
}
}
// 适配器类(将 Adaptee 转换为 Target)
class Adapter implements Target {
private Adaptee adaptee;
public Adapter(Adaptee adaptee) {
this.adaptee = adaptee;
}
@Override
public void request() {
adaptee.specificRequest(); // 调用 Adaptee 的方法
}
}
// 客户端使用
public class Client {
public static void main(String[] args) {
Adaptee adaptee = new Adaptee();
Target target = new Adapter(adaptee);
target.request(); // 输出:Adaptee specificRequest
}
}
装饰器模式
装饰器模式(Decorator Pattern)用于动态地为对象添加额外的功能,而无需修改其类结构。装饰器模式通过组合而非继承来实现功能的扩展,从而避免了继承带来的静态缺陷。
应用场景:
当需要给对象动态添加功能,并且这些功能可以被组合使用时。例如,Java 中的 InputStream 和 BufferedInputStream 就是典型的装饰器模式。
示例代码:
// 抽象组件
interface Component {
void operation();
}
// 具体组件
class ConcreteComponent implements Component {
@Override
public void operation() {
System.out.println("ConcreteComponent operation");
}
}
// 抽象装饰器
abstract class Decorator implements Component {
protected Component component;
public Decorator(Component component) {
this.component = component;
}
@Override
public void operation() {
component.operation();
}
}
// 具体装饰器 A
class ConcreteDecoratorA extends Decorator {
public ConcreteDecoratorA(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Added behavior from ConcreteDecoratorA");
}
}
// 具体装饰器 B
class ConcreteDecoratorB extends Decorator {
public ConcreteDecoratorB(Component component) {
super(component);
}
@Override
public void operation() {
super.operation();
addedBehavior();
}
private void addedBehavior() {
System.out.println("Added behavior from ConcreteDecoratorB");
}
}
// 客户端使用
public class Client {
public static void main(String[] args) {
Component component = new ConcreteComponent();
Component decoratedA = new ConcreteDecoratorA(component);
Component decoratedB = new ConcreteDecoratorB(decoratedA);
decoratedB.operation();
// 输出:
// ConcreteComponent operation
// Added behavior from ConcreteDecoratorA
// Added behavior from ConcreteDecoratorB
}
}
总结
- 目的不同:适配器模式用于解决接口不匹配问题,而装饰器模式用于动态扩展功能。
- 实现方式:适配器模式通常通过封装对象实现接口转换,装饰器模式通过组合对象实现功能叠加。
- 使用场景:适配器模式适用于接口适配,装饰器模式适用于动态添加功能。