适配器模式

发布时间: 更新时间: 总字数:759 阅读时间:2m 作者: IP上海 分享 网址

Convert the interface of a class into another interface clients expect.Adapter lets classes work togther that couldn’t otherwise because of incompatible interfaces.(将一个类的接口变成客户端所期待的另一种接口,从而使原本因接口不匹配而无法在一起工作的两个类能够在一起工作。)

适配器模式介绍

通用类图如下:

adapter

  • 适配器在生活有很多,比如说电源适配器,使电源电压变化
  • 说白了,我就是把一个接口或者类转换成其他的接口或类,如 Java-JDBC -> JDBC-ODBC bridge(不是桥接模式) -> ODBC -> SQLServer
  • Adapter 类似于 Wrapper 的实现

适配器模式分析

优点:

  • Adapter可以重定义Adaptee的部分行为
  • 允许Adapter与多个Adaptee一起工作
  • 可以让两个没有任何关系的类在一起运行
  • 增加了子类的透明性
  • 提高了类的复用度
  • 灵活性比较好

缺点:

  • 使得重定义Adaptee的行为比较困难,若想重定义需要生成Adaptee的子类,然后用Adapter引用其子类

适配器模式之实现

Golang

Java

首先是一个目标接口的代码:

public interface Target{
    //目标角色自己的方法
    public void request();
}

然后是目标角色的实现方法:

public class ConcreteTarget implements Target{
    public void request(){
        System.out.println("Nothing is important.");
    }
}

接下来是Adaptee的实现类,代码也会很少:

public class Adaptee{
    //原有业务逻辑
    public void doSth(){
        System.out.println("I want to eat delicious snacks");
    }
}

上面就是需要适配的类,在这里的方法什么的就不再多写了。接下来就是重中之重的适配器类的实现了:

public class Adapter extends Adaptee implements Target{
    public void request(){
        super.doSth();
    }
}

它继承自Adaptee,同时是Target的接口实现,这样一来就将Adaptee和Target联系起来了,最后是测试用的类:

public class Client{
    public static void main(String[] args) {
        //原有业务处理
        Target target = new ConcreteTarget();
        target.request();
        //现在增加了适配器角色之后的业务逻辑
        Target target2 = new Adapter();
        target2.request();
    }
}

适配器模式之应用场景

  • 你若想使用一个已经存在的类,而它的接口又不符合你的要求时,适配器模式走起。
  • 若你想创建一个可以复用的类,该类可以与其他不相关的类或不可预见的类协同工作时,适配器模式等着你。
  • 当你想使用一些已经存在的子类,但是不可能对每一个都进行子类化时,适配器模式欢迎你。
Home Archives Categories Tags Statistics
本文总阅读量 次 本站总访问量 次 本站总访客数