设计模式-结构型-适配器模式

123 阅读2分钟

简介

适配器模式是结构型模式的一种,被用于新接口和老接口之间的适配。在生活中也比较常见,比如我们的充电器,我们国家民用交流电标准输出是220V,但我们手机直接用直流电充电,且接受不了220V,因此需要我们的充电器做转换,此时我们的充电头就起到了一个适配的功能。一般来说,适配器分为对象适配器和类适配器,类适配器的写法通常是适配类继承另一个类然后实现一个接口(class adapter extends super implements interface),其实现也对应了其名称,即一个类要适配另一个类,通常都是通过继承实现;对象适配器的写法是通过构造函数将一个对象注入到适配类中,即将注入的类来干活。下面以手机充电的例子来分别Demo。

类适配器

1.首先定义中国电压类

public class ChinaStandardVoltage {
    public int getChinaStandardVoltage() {
        return 220;
    }
}

2.定义手机需要的电压接口

public interface PhoneVoltage {
    int getPhoneVoltage();
}

3.定义苹果手机充电的适配类

public class IphoneNeedVoltage extends ChinaStandardVoltage implements PhoneVoltage{
    @Override
    public int getPhoneVoltage() {
        int voltage = getChinaStandardVoltage();
        int iphoneVoltage = voltage / 44;
        return iphoneVoltage;
    }
}

4.定义一个手机类

public class Phone {
    public void charging(PhoneVoltage phoneVoltage) {
        if (phoneVoltage.getPhoneVoltage() == 5) {
            System.out.println("meet");
        } else {
            System.out.println("not meet");
        }
    }
}

5.客户端调用

public class Test {
    public static void main(String[] args) {
        Phone iphone = new Phone();
        iphone.charging(new IphoneNeedVoltage());//meet
    }
}

对象适配器

1.首先定义中国电压类

public class ChinaStandardVoltage {
    public int getChinaStandardVoltage() {
        return 220;
    }
}

2.定义手机需要的电压接口

public interface PhoneVoltage {
    int getPhoneVoltage();
}

3.定义苹果手机充电的适配类

public class IphoneNeedVoltage implements PhoneVoltage{

    private ChinaStandardVoltage voltage;
    public IphoneNeedVoltage(ChinaStandardVoltage voltage) {
        this.voltage = voltage;
    }

    @Override
    public int getPhoneVoltage() {
        int outVoltage = this.voltage.getChinaStandardVoltage();
        int iphoneVoltage = outVoltage / 44;
        return iphoneVoltage;
    }
}

4.定义一个手机类

public class Phone {
    public void charging(PhoneVoltage phoneVoltage) {
        if (phoneVoltage.getPhoneVoltage() == 5) {
            System.out.println("meet");
        } else {
            System.out.println("not meet");
        }
    }
}

5.客户端调用

public class Test {
    public static void main(String[] args) {
        Phone iphone = new Phone();
        ChinaStandardVoltage outVoltage = new ChinaStandardVoltage();
        iphone.charging(new IphoneNeedVoltage(outVoltage));//meet
    }
}