Fork me on GitHub

设计模式-适配器模式(09)

定义

  适配器模式(Adapter Pattern)又叫变压器模式。在适配器模式下,变压器的作用是把一种电压变换为另一种电压。

  英文原话是:Convert the interface of a class into another interface clients expect.Adapter lets classes work together that couldn't otherwise because of incompatible interfaces.

  意思是:将一个类的接口变换成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作

  适配器模式就是讲一个接口或类转换成其他的接口或类,适配器相当于一个包装器。适配器模式涉及三种角色:

    1.目标(Target)角色:该角色定义要转换成的目标接口。

    2.源(Adaptee)角色:需要被转换成目标角色的源角色。

    3.适配器(Adapter)角色:该角色是适配器模式的核心,其职责时通过集成或者类关联的方式,该源角色转换为目标角色。

 

/**
 * 源角色 
 */
public class Adaptee {
    //原有业务逻辑
    public void specificRequest(){
        System.out.println("源角色业务逻辑");
    }
}

/**
 * 目标角色 
 */
public interface Target {
    public void request();
}

/**
 * 适配器 
 * --要继承目标角色和源角色
 */
public class Adapter extends Adaptee implements Target {
    @Override
    public void request() {
        System.out.println("适配器改良开始");
        super.specificRequest();
        System.out.println("适配器改良结束");
    }
}

//调用
public class Client {
    public static void main(String[] args) {
        Target target = new Adapter();
        target.request();
    }
}

  源码

适配器的优点

  1. 适配器模式可以让两个没有任何关系的类在一起运行。
  2. 增加了类的透明度。
  3. 提高了类的复用度。
  4. 增强了代码的灵活性。

适配器的使用场景

      修改一个已经上线的系统时,需求对系统进行拓展,如果使用一个已有的类进行拓展,但这个类不符合系统中的接口,这时使用适配器模式是最合适的,这样就可以在不符合系统的接口的类转换成符合系统的接口、可以使用的类。

 

posted @ 2017-12-03 12:18  秋夜雨巷  阅读(186)  评论(0编辑  收藏  举报