结构型(五) - 适配器模式

一、概念

适配器模式(Adapter Pattern):这个模式就是用来做适配的,它将不兼容的接口转换为可兼容的接口,让原本由于接口不兼容而不能一起工作的类可以一起工作。

应用场景:适配器模式是一种事后的补救策略,我们在设计初期,就应该尽量规避掉接口不兼容的问题。

二、实现

这里借鉴了参考文章的例子,电源适配器。正常插排提供的电压是220V,但是我们的电子设备可能只需要5V电压,所以厂商会提供一个充电器,这个充电器就是适配的作用。

适配器模式有两种实现方式:类适配器和对象适配器。其中,类适配器使用继承关系来实现,对象适配器使用组合关系来实现。

  • 类适配器

1、目标接口

public interface PowerTarget {
    int output5V();
}

2、被适配类

public class PowerAdaptee {
    private int output =  220;

    public int output220V() {
        System.out.println("电源输出电压:" + output);
        return output;
    }
}

3、类适配器

public class ClassPowerAdapter extends PowerAdaptee implements PowerTarget{
    @Override
    public int output5V() {
        int output = output220V();
        System.out.println("原始的电压: " + output);
        output = output / 44;
        System.out.println("适配后电压: " + output);
        return output;
    }
}

4、测试类

public class Client {
    public static void main(String[] args) {
        ClassPowerAdapter classPowerAdapter = new ClassPowerAdapter();
        classPowerAdapter.output5V();
    }
}

5、运行结果:
适配器运行结果1.png

  • 对象适配器

1、对象适配器

public class ObjectPowerAdapter implements PowerTarget {
    private PowerAdaptee powerAdaptee;

    public ObjectPowerAdapter(PowerAdaptee adaptee) {
       this.powerAdaptee = adaptee;
    }

    @Override
    public int output5V() {
        int output = powerAdaptee.output220V();
        System.out.println("原始的电压: " + output);
        output = output / 44;
        System.out.println("适配后电压: " + output);
        return output;
    }
}

2、测试类

public class Client {
    public static void main(String[] args) {
        ClassPowerAdapter classPowerAdapter = new ClassPowerAdapter();
        classPowerAdapter.output5V();
        System.out.println("---------------------");
        ObjectPowerAdapter objectPowerAdapter = new ObjectPowerAdapter(new PowerAdaptee());
        objectPowerAdapter.output5V();
    }
}

3、运行结果:
适配器运行结果2.png

  • 两种实现的使用场景

1、如果 Adaptee 接口并不多,那两种实现方式都可以。

2、如果 Adaptee 接口很多,而且 AdapteeITarget 接口定义大部分都相同,那我们推荐使用类适配器,因为 Adaptor 复用父类 Adaptee 的接口,比起对象适配器的实现方式,Adaptor 的代码量要少一些。

3、如果 Adaptee 接口很多,而且 AdapteeITarget 接口定义大部分都不相同,那我们推荐使用对象适配器,因为组合结构相对于继承更加灵活。

如果接口不多,我个人觉得对象适配器更好些,因为在调用的时候会把被适配器类传递进去,这样看代码的时候就能知道是对哪个类进行了适配,以后修改的时候也会注意。

参考文章:
适配器模式(adapter pattern)
极客时间《设计模式》(王争)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值