Java设计模式之适配器模式

适配器模式是指将一个类的接口转换成用户期望的另一个接口,使得原本不兼容的类可以一起工作。比如:手机充电需要5V的电压,而生活供电是220V电压,所以给手机充电就需要一个5V的充电器,这个充电器就是适配器。由此可见,适配器模式的出现是为了解决现有的类或接口不能满足需求,且无法直接修改的问题。
适配器模式包含的角色如下:

  • 被适配者(Adaptee):比如:220V的电压就是被适配者,表示已经存在的类或对象;
  • 目标角色(Target):比如:5V电压就是目标角色,也就是我们的期望接口、抽象类或具体类;
  • 适配器(Adapter):比如:充电器就是适配器,它可以调用Adaptee和Target进行适配;
    总之一句话,适配器模式是指Adapter可以根据Target接口中的方法来调用Adaptee中的方法。
    其实现方案有两种:类适配器和对象适配器。

类适配器

public class Adaptee {

    public int output220V() {
        int output = 220;
        System.out.println("输出" + output + "V电压");
        return output;
    }
}
public interface Target {

    int output5V();
}
public class Adapter extends Adaptee implements Target {
    @Override
    public int output5V() {
        int output = super.output220V() / 44;
        System.out.println("输出" + output + "V电压");
        return output;
    }
}
public class Test {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.output5V();
    }
}
输出220V电压
输出5V电压

对象适配器

public class Adapter implements Target {

    private Adaptee adaptee;

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

    @Override
    public int output5V() {
        int output = adaptee.output220V() / 44;
        System.out.println("输出" + output + "V电压");
        return output;
    }
}
public class Test {
    public static void main(String[] args) {
        Target target = new Adapter(new Adaptee());
        target.output5V();
    }
}

总结

  • 系统需要使用一些现有的类,这些类的接口(方法名等)无法改变且不符合需要,则可以用适配器模式;
  • 类适配器一次最多只能适配一个Adaptee,因为Java不支持多继承。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值