Java设计模式之适配器模式(Adapter)

123 阅读2分钟

适配器模式(Adapter Pattern)是一种结构型设计模式,用于使原本不兼容的接口能够一起工作。这种模式通常用于将一个类的接口转换成客户期望的另一个接口,使得原本由于接口不兼容而不能一起工作的类可以一起工作。

适配器模式包含以下几个关键角色:

  1. Target(目标接口) :客户所期待的接口。
  2. Adaptee(被适配者) :一个已经存在的类,需要适配。
  3. Adapter(适配器) :通过在内部包装一个Adaptee对象,把源接口转换成目标接口。

适配器模式的典型代码结构如下:

// 目标接口
interface Target {
    void request();
}

// 被适配者
class Adaptee {
    public void specificRequest() {
        System.out.println("Made a specific request to the Adaptee.");
    }
}

// 适配器
class Adapter implements Target {
    private Adaptee adaptee;

    public Adapter(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    @Override
    public void request() {
        adaptee.specificRequest();
    }
}

使用适配器模式的示例:

public class AdapterDemo {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new Adapter(adaptee);
        target.request(); // 通过适配器调用被适配者的方法
    }
}

输出结果:

Made a specific request to the Adaptee.

适配器模式的优点包括:

  • 兼容性:使得原本不兼容的接口可以一起工作。
  • 灵活性:可以在运行时动态地切换适配器来改变对象之间的接口。
  • 解耦:目标接口与被适配者之间的耦合度降低。

适配器模式的缺点包括:

  • 增加系统的复杂性:每增加一个被适配者,就需要增加一个适配器类。
  • 降低性能:在某些情况下,使用适配器模式可能会降低系统性能。

适配器模式适用于以下场景:

  • 当需要使用一个已经存在的类,但这个类的接口不符合系统的需要。
  • 当想要创建一个可以复用的类,用于与一个或多个不兼容的接口一起工作。
  • 当需要统一多个有相同功能的类的接口时。

适配器模式有两种变体:

  1. 类适配器模式:通过多重继承来实现,Java语言不支持多重继承,但可以使用内部类来模拟。
  2. 对象适配器模式:使用一个内部的被适配者对象来实现,上面给出的示例就是对象适配器模式。