20、适配器模式(Adapter Pattern)

2020-08-25  本文已影响0人  火山_6c7b

1. 适配器模式

1.1 简介

  适配器模式(Adapter Pattern)是结构型模式。主要用来解决接口不兼容的问题,将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。定义一个包装类,用于包装不兼容接口的对象。

  适配器模式有Adaptee(被适配者)和Adaptor(适配器)两个角色,分为对象适配器模式和类适配器模式。对象适配器模式是指Adaptor(适配器)持有Adaptee(被适配者)对象,通过调用Adaptee的方法,来对其进行修饰等操作。而类适配器模式是指Adaptor(适配器)继承Adaptee(被适配者)类,可以直接拥有Adaptee方法,从而来对其做各种动作(不能改变原方法)。

  还有一种叫Pluggable Adapters,可以动态的获取几个adapters中一个。使用Reflection技术,可以动态的发现类中的Public方法。

1.2 对象适配器模式

对象适配器模式uml:

对象适配器uml.jpg

  对象适配器非常类似之前的装饰器模式,都是通过组合/聚合来达到扩展的效果。

1.3 类适配器模式

类适配器模式uml:

类适配器模式uml.jpg

  类适配器通过继承/实现来扩展,需要考虑带来的耦合。

适配器模式角色:

2. 示例

  例如我们有台macbook,想外接一个显示器,但显示器的接口是type-c,macbook的lightning接口不能直接使用。因此需要一个转接头,将lightning接口转换成type-c接口,使macbook可以连接type-c的显示器。

  type-c接口是Target,lightning接口是Adaptee,整个转接头就是Adapter。

目标类:

public interface TypeC {
    void useTypeCPort();
}

适配者类:

public class Lightning {
    public void extent() {
        System.out.println("通过lightning接口外接显示器");
    }
}

对象适配器:

public class PortObjectAdapter implements TypeC {
    private Lightning lightning;

    public PortObjectAdapter(Lightning lightning) {
        this.lightning = lightning;
    }

    @Override
    public void useTypeCPort() {
        System.out.println("使用type-c转接头");
        lightning.extent();
    }
}

类适配器:

public class PortClassAdapter extends Lightning implements TypeC {
    @Override
    public void useTypeCPort() {
        System.out.println("使用type-c转接头");
        super.extent();
    }
}

两种模式调用示例:

    public static void main(String[] args) {  
        //对象适配器
        System.out.println("----对象适配器----");
        Lightning lightning = new Lightning();
        PortObjectAdapter adapter = new PortObjectAdapter(lightning);
        adapter.useTypeCPort();
        //类适配器
        System.out.println("----类适配器----");
        PortClassAdapter adapter1 = new PortClassAdapter();
        adapter1.useTypeCPort();
    } 

3. 总结

适配器模式优点:

适配器模式缺点:

类和对象的适配器模式比较:

上一篇 下一篇

猜你喜欢

热点阅读