设计模式 ~ 结构型模式 ~ 适配器模式 ~ Adapter Pattern。

设计模式 ~ 结构型模式 ~ 适配器模式 ~ Adapter Pattern。



将一个类的接口转换成客户希望的另一个接口。Adapter 模式使得原本由于接口不兼容而不能一起工作的那些类可以在一起工作。

结构。

  • 目标(Target)接口。
    当前业务系统所期待的接口。目标可以是具体的或抽象的类,也可以是接口。

  • 需要适配的类(适配者类 Adaptee )。
    是被访问和适配的现存组件库中的组件接口。

  • 适配器(Adapter)
    ta 是一个转换器,通过继承或引用适配者的对象,把适配者接口转换成目标接口,让客户按目标接口的格式访问适配者。

【eg.】读卡器。

类适配器模式。

现有一台电脑只能读取SD卡,而要读取TF卡中的内容的话就需要使用到适配器模式。创建一个读卡器,将TF卡中的内容读取出来。

类图如下。

在这里插入图片描述

package com.geek.adapter.pattern.class1.adapter;

/**
 * 适配者类的接口。
 *
 * @author geek
 */
public interface ITfCard {

    /**
     * 读。
     *
     * @return
     */
    String readTf();

    /**
     * 写。
     *
     * @param msg
     */
    void writeTf(String msg);

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * 适配者类。
 *
 * @author geek
 */
public class TfCardImpl implements ITfCard {

    /**
     * 读。
     *
     * @return
     */
    @Override
    public String readTf() {
        return "TF card 读数据。 ~ hello world。";
    }

    /**
     * 写。
     *
     * @param msg
     */
    @Override
    public void writeTf(String msg) {
        System.out.println("Tf card 写数据。 ~ " + msg);
    }

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * 目标接口。
 *
 * @author geek
 */
public interface ISdCard {

    /**
     * 读。
     *
     * @return
     */
    String readSd();

    /**
     * 写。
     *
     * @param msg
     */
    void writeSd(String msg);

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * 具体的 sd 卡。
 *
 * @author geek
 */
public class SdCardImpl implements ISdCard {

    /**
     * 读。
     *
     * @return
     */
    @Override
    public String readSd() {
        return "SD card 读数据。 ~ hello world。";
    }

    /**
     * 写。
     *
     * @param msg
     */
    @Override
    public void writeSd(String msg) {
        System.out.println("SD card 写数据。 ~ " + msg);
    }

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * 计算机类。
 *
 * @author geek
 */
public class Computer {

    /**
     * 从 sd 卡中读取数据。
     *
     * @param sdCard
     * @return
     */
    public String readSd(ISdCard sdCard) {
        if (sdCard == null) {
            throw new NullPointerException("sd card cannot be null.");
        }
        return sdCard.readSd();
    }

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * 适配器类。
 *
 * @author geek
 */
public class SdAdapterTf extends TfCardImpl implements ISdCard {

    /**
     * 读。
     *
     * @return
     */
    @Override
    public String readSd() {
        System.out.println(" ~ SdAdapterTf ~ read tf card.");
        // TfCardImpl。
        return readTf();
    }

    /**
     * 写。
     *
     * @param msg
     */
    @Override
    public void writeSd(String msg) {
        System.out.println(" ~ SdAdapterTf ~ write tf card.");
        // TfCardImpl。
        writeTf(msg);
    }

}

package com.geek.adapter.pattern.class1.adapter;

/**
 * @author geek
 */
public class Client {

    public static void main(String[] args) {
        // 创建计算机对象。
        Computer computer = new Computer();
        // 读取 SD 卡中的数据。
        String msg = computer.readSd(new SdCardImpl());
        System.out.println("msg = " + msg);

        System.out.println("~ ~ ~ ~ ~ ~ ~");

        // 使用该电脑读取 TF 卡中的数据。
        // 适配器。
        String msg1 = computer.readSd(new SdAdapterTf());
        System.out.println("msg1 = " + msg1);
    }

}

/*
Connected to the target VM, address: '127.0.0.1:53396', transport: 'socket'
msg = SD card 读数据。 ~ hello world。
~ ~ ~ ~ ~ ~ ~
 ~ SdAdapterTf ~ read tf card.
msg1 = TF card 读数据。 ~ hello world。
Disconnected from the target VM, address: '127.0.0.1:53396', transport: 'socket'

Process finished with exit code 0
 */

类适配器模式违背了合成复用原则。类适配器是客户类有一个接口规范的情况下可用,反之不可用。



对象适配器模式。

实现方式:对象适配器模式可釆用将现有组件库中已经实现的组件引入适配器类中,该类同时实现当前系统的业务接口。

我们使用对象适配器模式将读卡器的案例进行改写。类图如下。

在这里插入图片描述
代码如下。

类适配器模式的代码,我们只需要修改适配器类(SdAdapterTf)和测试类。

package com.geek.adapter.pattern.object.adapter;

import com.geek.adapter.pattern.class1.adapter.ITfCard;

/**
 * 适配器类。
 *
 * @author geek
 */
public class SdAdapterTf implements ISdCard {

    /**
     * 声明适配者类。
     */
    private final ITfCard tfCard;

    public SdAdapterTf(ITfCard tfCard) {
        this.tfCard = tfCard;
    }

    /**
     * 读。
     *
     * @return
     */
    @Override
    public String readSd() {
        System.out.println(" ~ SdAdapterTf ~ read sd card.");
        return this.tfCard.readTf();
    }

    /**
     * 写。
     *
     * @param msg
     */
    @Override
    public void writeSd(String msg) {
        System.out.println(" ~ SdAdapterTf ~ write tf card.");
        this.tfCard.writeTf(msg);
    }

}

package com.geek.adapter.pattern.object.adapter;

import com.geek.adapter.pattern.class1.adapter.TfCardImpl;

/**
 * @author geek
 */
public class Client {

    public static void main(String[] args) {
        // 创建计算机对象。
        Computer computer = new Computer();
        // 读取 SD 卡中的数据。
        String msg = computer.readSdCard(new SdCardImpl());
        System.out.println("msg = " + msg);

        System.out.println("~ ~ ~ ~ ~ ~ ~");

        // 使用该电脑读取 TF 卡中的数据。
        // 适配器。
//        String msg1 = computer.readSdCard(new SdAdapterTf());
//        System.out.println("msg1 = " + msg1);

        // 创建适配器类对象。
        TfCardImpl tfCard = new TfCardImpl();
        SdAdapterTf sdAdapterTf = new SdAdapterTf(tfCard);
        String msg1 = computer.readSdCard(sdAdapterTf);
        System.out.println("msg1 = " + msg1);
    }

}

/*
Connected to the target VM, address: '127.0.0.1:53991', transport: 'socket'
msg = SD card 读数据。
~ ~ ~ ~ ~ ~ ~
 ~ SdAdapterTf ~ read sd card.
msg1 = TF card 读数据。 ~ hello world。
Disconnected from the target VM, address: '127.0.0.1:53991', transport: 'socket'

Process finished with exit code 0
 */

注意:还有一个适配器模式是接口适配器模式。当不希望实现一个接口中所有的方法时,可以创建一个抽象类 Adapter ,实现所有方法。而此时我们只需要继承该抽象类即可。



应用场景。

  • 以前开发的系统存在满足新系统功能需求的类,但其接口同新系统的接口不一致。

  • 使用第三方提供的组件,但组件接口定义和自己要求的接口定义不同。



JDK 源码解析。

Reader(字符流)、InputStream(字节流)的适配使用的是 InputStreamReader。

InputStreamReader 继承自 java.io 包中的 Reader,对他中的抽象的未实现的方法给出实现。

/*
 * Copyright (c) 1996, 2013, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 *
 */

package java.io;

import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import sun.nio.cs.StreamDecoder;


/**
 * An InputStreamReader is a bridge from byte streams to character streams: It
 * reads bytes and decodes them into characters using a specified {@link
 * java.nio.charset.Charset charset}.  The charset that it uses
 * may be specified by name or may be given explicitly, or the platform's
 * default charset may be accepted.
 *
 * <p> Each invocation of one of an InputStreamReader's read() methods may
 * cause one or more bytes to be read from the underlying byte-input stream.
 * To enable the efficient conversion of bytes to characters, more bytes may
 * be read ahead from the underlying stream than are necessary to satisfy the
 * current read operation.
 *
 * <p> For top efficiency, consider wrapping an InputStreamReader within a
 * BufferedReader.  For example:
 *
 * <pre>
 * BufferedReader in
 *   = new BufferedReader(new InputStreamReader(System.in));
 * </pre>
 *
 * @see BufferedReader
 * @see InputStream
 * @see java.nio.charset.Charset
 *
 * @author      Mark Reinhold
 * @since       JDK1.1
 */

public class InputStreamReader extends Reader {

    private final StreamDecoder sd;

    /**
     * Creates an InputStreamReader that uses the default charset.
     *
     * @param  in   An InputStream
     */
    public InputStreamReader(InputStream in) {
        super(in);
        try {
            sd = StreamDecoder.forInputStreamReader(in, this, (String)null); // ## check lock object
        } catch (UnsupportedEncodingException e) {
            // The default encoding should always be available
            throw new Error(e);
        }
    }

    /**
     * Creates an InputStreamReader that uses the named charset.
     *
     * @param  in
     *         An InputStream
     *
     * @param  charsetName
     *         The name of a supported
     *         {@link java.nio.charset.Charset charset}
     *
     * @exception  UnsupportedEncodingException
     *             If the named charset is not supported
     */
    public InputStreamReader(InputStream in, String charsetName)
        throws UnsupportedEncodingException
    {
        super(in);
        if (charsetName == null)
            throw new NullPointerException("charsetName");
        sd = StreamDecoder.forInputStreamReader(in, this, charsetName);
    }

    /**
     * Creates an InputStreamReader that uses the given charset.
     *
     * @param  in       An InputStream
     * @param  cs       A charset
     *
     * @since 1.4
     * @spec JSR-51
     */
    public InputStreamReader(InputStream in, Charset cs) {
        super(in);
        if (cs == null)
            throw new NullPointerException("charset");
        sd = StreamDecoder.forInputStreamReader(in, this, cs);
    }

    /**
     * Creates an InputStreamReader that uses the given charset decoder.
     *
     * @param  in       An InputStream
     * @param  dec      A charset decoder
     *
     * @since 1.4
     * @spec JSR-51
     */
    public InputStreamReader(InputStream in, CharsetDecoder dec) {
        super(in);
        if (dec == null)
            throw new NullPointerException("charset decoder");
        sd = StreamDecoder.forInputStreamReader(in, this, dec);
    }

    /**
     * Returns the name of the character encoding being used by this stream.
     *
     * <p> If the encoding has an historical name then that name is returned;
     * otherwise the encoding's canonical name is returned.
     *
     * <p> If this instance was created with the {@link
     * #InputStreamReader(InputStream, String)} constructor then the returned
     * name, being unique for the encoding, may differ from the name passed to
     * the constructor. This method will return <code>null</code> if the
     * stream has been closed.
     * </p>
     * @return The historical name of this encoding, or
     *         <code>null</code> if the stream has been closed
     *
     * @see java.nio.charset.Charset
     *
     * @revised 1.4
     * @spec JSR-51
     */
    public String getEncoding() {
        return sd.getEncoding();
    }

    /**
     * Reads a single character.
     *
     * @return The character read, or -1 if the end of the stream has been
     *         reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    public int read() throws IOException {
        return sd.read();
    }

    /**
     * Reads characters into a portion of an array.
     *
     * @param      cbuf     Destination buffer
     * @param      offset   Offset at which to start storing characters
     * @param      length   Maximum number of characters to read
     *
     * @return     The number of characters read, or -1 if the end of the
     *             stream has been reached
     *
     * @exception  IOException  If an I/O error occurs
     */
    public int read(char cbuf[], int offset, int length) throws IOException {
        return sd.read(cbuf, offset, length);
    }

}

如上代码中的 sd(StreamDecoder 类对象),在 Sun 的 JDK 实现中,实际的方法实现是对 sun.nio.cs.StreamDecoder 类的同名方法的调用封装。类结构图如下。

在这里插入图片描述
从上图可以看出。

  • InputStreamReader 是对同样实现了 Reader 的 StreamDecoder 的封装。

  • StreamDecoder 不是 Java SE API 中的内容,是 Sun JDK 给出的自身实现。但我们知道他们对构造方法中的字节流类(InputStream)进行封装,并通过该类进行了字节流和字符流之间的解码转换。

结论:

从表层来看,InputStreamReader 做了 InputStream 字节流类到 Reader 字符流之间的转换。而从如上 Sun JDK 中的实现类关系结构中可以看出,是 StreamDecoder 的设计实现在实际上采用了适配器模式。


在这里插入图片描述
在这里插入图片描述

package com.geek.adapter;

/**
 * 要被适配的类 ~ 网线。
 *
 * @author geek
 */
public class Adaptee {

    public void request() {
        System.out.println("连接网线上网。");
    }

}

package com.geek.adapter;

/**
 * 接口转换器的抽象 ~ 接口。
 *
 * @author geek
 */
public interface INetToUsb {

    /**
     * 处理请求。网线 -> USB。
     */
    void handleRequest();

}

package com.geek.adapter;

// 继承 ~ 类适配器,单继承。
// 组合 ~ 对象适配器。(常用)。

/**
 * 适配器 ~ 需要连接 USB + 连接网线。
 *
 * @author geek
 */
public class Adapter extends Adaptee implements INetToUsb {

    /**
     * 处理请求。网线 -> USB。
     */
    @Override
    public void handleRequest() {
        super.request();// 可以上网了。
    }

}

package com.geek.adapter;

/**
 * 客户端。不能插网线的电脑,想上网。
 */
public class Computer {

    public static void main(String[] args) {
        // 电脑,适配器,网线。
        Computer computer = new Computer();// 电脑。
        Adaptee adaptee = new Adaptee();// 网线。// 适配器集成了网线。public class Adapter extends Adaptee implements INetToUsb {
        Adapter adapter = new Adapter();// 转接器。

        computer.net(adapter);
    }

    public void net(INetToUsb adapter) {
        // 上网的具体实现 ~ 找一个转接头。
        adapter.handleRequest();
    }

}

  • 组合方式。
package com.geek.adapter;

// 组合 ~ 对象适配器。(常用)。

public class Adapter2 implements INetToUsb {

    private Adaptee adaptee;

    public Adapter2(Adaptee adaptee) {
        this.adaptee = adaptee;
    }

    /**
     * 处理请求。网线 -> USB。
     */
    @Override
    public void handleRequest() {
        adaptee.request();// 可以上网了。
    }

}

上网。

package com.geek.adapter;

/**
 * 客户端。不能插网线的电脑,想上网。
 *
 * @author geek
 */
public class Computer2 {

    public static void main(String[] args) {
        // 电脑,适配器,网线。
        Computer2 computer = new Computer2();// 电脑。
        Adaptee adaptee = new Adaptee();// 网线。// 适配器集成了网线。public class Adapter extends Adaptee implements INetToUsb {
        Adapter2 adapter2 = new Adapter2(adaptee);// 转接器。

        computer.net(adapter2);
    }

    public void net(INetToUsb adapter) {
        // 上网的具体实现 ~ 找一个转接头。
        adapter.handleRequest();
    }

}



对象适配器优点。
  • 一个适配器可以把多个不同的适配者适配到同一个目标。
  • 可以适配一个适配者的子类。有雨适配器和适配者之间是关联关系,根据“里氏代换原则”,适配者的子类也可以通过该适配器进行适配。


类适配器的缺点。
  • 对于 Java、C# 等不支持多重类继承的语言,一次最多只能适配一个适配者类,不能同时适配多个适配者。

  • 在 Java、C# 等语言中,类适配器模式中的目标抽象类只能为接口,不能是类,其使用有一定的局限性。



使用场景。
  • 系统需要使用一些现有的类,而这些类的接口(如方法名)不符合系统的需要,甚至没有这些类的源代码。

  • 想创建一个可以重复使用的类,用于与一些彼此没有太大关联的一些类,包括一些可能在将来引进的类一起工作。

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

lyfGeek

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值