首页
学习
活动
专区
圈层
工具
发布

复习:GoF的23种设计模式之adapter模式(结构型)

adapter模式(适配器模式)

什么是适配器模式呢?? 我先讲一个小小的生活常识吧,我们现在的家用电源是交流电220V的,电子元件大都是使用直流电的,就好比笔记本电脑,电源线上加有一个大大的适配器。此适配器的作用:将220V的交流电(被适配)转换(适配器)为24V的直流电(需求)。

在设计模式中,适配器模式,是将一个类的接口转换成用户所需要的,使得两个不同接口的类能再次一起工作。有两类适配器:

第一类:类适配器,需求方只是接口,使用适配器 继承 被适配类。

第二类:对象适配器,需求方也是类,使用 适配器 委托\依赖 被适配类。

示例代码 (类适配器,转换器继承被转换对象)

代码语言:javascript
复制
class AcPowerAdaptee{    //被适配  可以是稳定现成代码、新版本代码
    public String getAc() {
        return "220V交流电";
    }
}
interface DcPowerDemand{   //需求方  想使用老代码、 版本兼容
    public String getDc();
}
class powerAdapter extends AcPowerAdaptee implements DcPowerDemand {  //转换器  
    public String getDc() {
        return getAc()+"将被转换成12V直流电";
    }
}
public class AdapterTest {  //调用者
    public static void main(String[] args) {
        DcPowerDemand demand = new powerAdapter();
        System.out.println(demand.getDc());
    }
}

UML类图

下一篇
举报
领券