设计模式学习 - 适配器模式

学习、梳理设计模式。

适配器模式

不兼容的转换为兼容的,为解决兼容问题而生。

实现方式可分为组合方式和继承方式。

举个例子,充电宝只能用二相电供电,但现在只有三相电该怎么办呢?

三相电实例

/**
 * 三相电
 */
public class ThreePlug {

    public void powerWithThree() {
        System.out.println("使用三相供电");
    }
}

二相电接口

/**
 * 二相接口
 */
public interface TwoPlugInterface {

    /**
     * 二相电流供电
     */
    void powerWithTwo();
}

充电宝

/**
 * 充电宝
 */
public class PowerBank {

    /**
     * 需要二相供电
     */
    private TwoPlugInterface twoPlugInterface;

    public PowerBank(TwoPlugInterface twoPlugInterface) {
        this.twoPlugInterface = twoPlugInterface;
    }

    public void power() {
        twoPlugInterface.powerWithTwo();
    }
}

组合方式

我们来定义个三相适配器(接收三相电,对外提供二相电)。

public class ThreePlugAdapter implements TwoPlugInterface {

    private ThreePlug threePlug;

    public ThreePlugAdapter(ThreePlug threePlug) {
        this.threePlug = threePlug;
    }

    @Override
    public void powerWithTwo() {
        threePlug.powerWithThree();
    }

}

测试一把

public class PowerBankTest {

    public static void main(String[] args) {

        // 现在只有三相电
        ThreePlug threePlug = new ThreePlug();

        // 通过三相转二相适配器进行转换
        TwoPlugInterface twoPlugInterface= new ThreePlugAdapter(threePlug);

        PowerBank powerBank = new PowerBank(twoPlugInterface);
        powerBank.power();
    }

}

输出

使用三相供电

继承方式

继承的方式从代码上来看比较简洁

public class ThreePlugAdapter extends ThreePlug implements TwoPlugInterface {

    @Override
    public void powerWithTwo() {
        this.powerWithThree();
    }

}

测试一把

public class PowerBankTest {

    public static void main(String[] args) {

        TwoPlugInterface twoPlugInterface = new ThreePlugAdapter();
        PowerBank powerBank = new PowerBank(twoPlugInterface);
        powerBank.power();

    }

输出

使用三相供电