(结构型模式)适配器模式

140 阅读2分钟

简介

适配器模式(Adapter Pattern)是作为两个不兼容的接口之间的桥梁。这种类型的设计模式属于结构型模式,它结合了两个独立接口的功能。比如常见的mac笔记本上,要插入usb接口,但是它本身只提供了个type-c接口,就需要一个转接头来帮我们进行usb到type-c的转换。

适配器中的角色

Client(请求者)

调用者,也就是需要使用转换接头的人。Client希望能够通过调用定义好的Target接口就能够完成他希望的功能,而不需要关心功能实现真实细节。

Target(目标)

目标角色也就是期望的接口

Adapter(适配器)

进行接口转换的具体细节实现实例。

Adaptee(被适配对象)

需要被适配器转换的角色。

实际开发示例

接入第三方的电商api(淘宝,拼多多),我们需要获取商品可选属性菜单返回到前端页面,比如同一个商品女装,在请求淘宝和请求拼多多返回的字段肯定是不一样的,我们就能用到适配器模式进行整合统一的返回数据。

类适配器模式

Tatget(目标)

public interface Target {

    /**
     * 获取商品可选属性
     * @param goodId
     * @return
     */
    List<BasicProperty> findGoodProperty(Long goodId);

}

Adaptee(被适配对象)

public class TbAdaptee {

    public List<TbProperty> findTbProperty(Long goodId){
        // 调用tb api
        return new ArrayList<>();
    }
}

Adapter(适配器)

public class Adapter extends TbAdaptee implements Target{

    @Override
    public List<BasicProperty> findGoodProperty(Long goodId) {
        //调用被适配对象对象
        List<TbProperty> tbProperty = findTbProperty(goodId);
        //转换逻辑.....
        return new ArrayList<>();
    }
}

Client(请求者)

public class Demo {

    public static void main(String[] args) {
        Adapter adapter = new Adapter();
        List<BasicProperty> goodProperty = adapter.findGoodProperty(1L);
    }
}

对象适配器模式

对象适配器模式只需要在适配器上修改即可。

Adapter(适配器)

public class Adapter implements Target{
    
    private TbAdaptee tbAdaptee;
    
    public Adapter(){
        this.tbAdaptee = new TbAdaptee();
    }

    @Override
    public List<BasicProperty> findGoodProperty(Long goodId) {
        //调用被适配对象对象
        List<TbProperty> tbProperty = tbAdaptee.findTbProperty(goodId);
        //转换逻辑.....
        return new ArrayList<>();
    }
}