前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >设计模式学习 - 适配器模式

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

作者头像
许杨淼淼
发布2019-12-29 20:10:36
3350
发布2019-12-29 20:10:36
举报
文章被收录于专栏:醉程序醉程序

学习、梳理设计模式。

适配器模式

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

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

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

三相电实例

代码语言:javascript
复制
/**
 * 三相电
 */
public class ThreePlug {

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

二相电接口

代码语言:javascript
复制
/**
 * 二相接口
 */
public interface TwoPlugInterface {

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

充电宝

代码语言:javascript
复制
/**
 * 充电宝
 */
public class PowerBank {

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

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

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

组合方式

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

代码语言:javascript
复制
public class ThreePlugAdapter implements TwoPlugInterface {

    private ThreePlug threePlug;

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

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

}

测试一把

代码语言:javascript
复制
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();
    }

}

输出

使用三相供电

继承方式

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

代码语言:javascript
复制
public class ThreePlugAdapter extends ThreePlug implements TwoPlugInterface {

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

}

测试一把

代码语言:javascript
复制
public class PowerBankTest {

    public static void main(String[] args) {

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

    }

输出

使用三相供电

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2018年12月23日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 适配器模式
    • 组合方式
      • 继承方式
      领券
      问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档