设计模式:适配器模式

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

适配器模式的应用场景

  1. 遗留系统的兼容:需要将一个新的接口与旧系统结合。
  2. 接口转换:需要将一个类的接口转换为另一个接口。
  3. 复用现有类:想复用一些现有的类,但接口与当前系统不兼容。

适配器模式的两种实现方式

  1. 类适配器模式:通过继承来实现适配器功能。由于Java不支持多继承,因此它主要通过单一继承来实现。
  2. 对象适配器模式:通过组合来实现适配器功能,即适配器包含一个被适配的对象,并实现目标接口。

类适配器模式示例

假设我们有一个Target接口和一个已有的Adaptee类。我们想让Adaptee能够兼容Target接口。

Target接口
public interface Target {
    void request();
}
Adaptee类
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee's specific request.");
    }
}
类适配器
public class ClassAdapter extends Adaptee implements Target {
    @Override
    public void request() {
        // 将请求委派给Adaptee的方法
        specificRequest();
    }
}
使用类适配器
public class Client {
    public static void main(String[] args) {
        Target target = new ClassAdapter();
        target.request();  // 输出: Adaptee's specific request.
    }
}

对象适配器模式示例

与类适配器不同,对象适配器使用组合来实现适配。

Target接口
public interface Target {
    void request();
}
Adaptee类
public class Adaptee {
    public void specificRequest() {
        System.out.println("Adaptee's specific request.");
    }
}
对象适配器
public class ObjectAdapter implements Target {
    private Adaptee adaptee;

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

    @Override
    public void request() {
        // 将请求委派给Adaptee的方法
        adaptee.specificRequest();
    }
}
使用对象适配器
public class Client {
    public static void main(String[] args) {
        Adaptee adaptee = new Adaptee();
        Target target = new ObjectAdapter(adaptee);
        target.request();  // 输出: Adaptee's specific request.
    }
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值