适配器模式(Adapter Pattern)——随遇而安

前言

来看看某宝的爆款吧!什么十三合一的读卡器?是不是很厉害?!

这里写图片描述

读卡器作为内存卡和笔记本之间的适配器。将内存卡插入读卡器,再讲读卡器插入笔记本,这样就可以通过笔记本读取内存卡。无论你是什么型号的内存卡,通过读卡器都能通过USB接口接入电脑。可以说读卡器就是一种适配器。

概述

定义

适配器模式(Adapter Pattern)讲一个类的接口。转化成客户期望的另外另一种接口。适配器让原本接口不兼容的类可以合作无间。

说明

​ 这个模式可以通过创建适配器进行接口转换,让不兼容的接口变成兼容。这可以让客户从实现的接口解耦。如果在一段时间之后,我们想要改变接口,适配器可以将改变的部分封装起来,客户就不必为了应付不同的接口而每次跟着修改。

类图

对象适配器类图

这里写图片描述

Target:目标抽象类

Adapter:适配器类

Adaptee:适配者类

Client:客户类

这个适配器模式充满着良好的OO设计原则:使用对象组合,以修改的接口包装被适配者:这种做做法还有额外的优点,那就是,被适配者的任何子类,都可以搭配适配器使用。

类适配器类图(需要多重继承,不适合java)

这里写图片描述

设计模式的实现

背景

在jdk 1.0中有这样一段代码

package java.util;
/**
    ……

 * @see     java.util.Iterator
 * @see     java.io.SequenceInputStream
 * @see     java.util.Enumeration#nextElement()
 * @see     java.util.Hashtable
 * @see     java.util.Hashtable#elements()
 * @see     java.util.Hashtable#keys()
 * @see     java.util.Vector
 * @see     java.util.Vector#elements()
 *
 * @author  Lee Boynton
 * @since   JDK1.0
 */
public interface Enumeration<E> {
    /**
     * Tests if this enumeration contains more elements.
     *
     * @return  <code>true</code> if and only if this enumeration object
     *           contains at least one more element to provide;
     *          <code>false</code> otherwise.
     */
    boolean hasMoreElements();

    /**
     * Returns the next element of this enumeration if this enumeration
     * object has at least one more element to provide.
     *
     * @return     the next element of this enumeration.
     * @exception  NoSuchElementException  if no more elements exist.
     */
    E nextElement();
}

在JDK 1.2 中还有这样一段代码:

package java.util;

import java.util.function.Consumer;

/**
    ……

 * @param <E> the type of elements returned by this iterator
 *
 * @author  Josh Bloch
 * @see Collection
 * @see ListIterator
 * @see Iterable
 * @since 1.2
 */
public interface Iterator<E> {
    /**
     * Returns {@code true} if the iteration has more elements.
     * (In other words, returns {@code true} if {@link #next} would
     * return an element rather than throwing an exception.)
     *
     * @return {@code true} if the iteration has more elements
     */
    boolean hasNext();

    /**
     * Returns the next element in the iteration.
     *
     * @return the next element in the iteration
     * @throws NoSuchElementException if the iteration has no more elements
     */
    E next();

    /**
     * Removes from the underlying collection the last element returned
     * by this iterator (optional operation).  This method can be called
     * only once per call to {@link #next}.  The behavior of an iterator
     * is unspecified if the underlying collection is modified while the
     * iteration is in progress in any way other than by calling this
     * method.
     *
     * @implSpec
     * The default implementation throws an instance of
     * {@link UnsupportedOperationException} and performs no other action.
     *
     * @throws UnsupportedOperationException if the {@code remove}
     *         operation is not supported by this iterator
     *
     * @throws IllegalStateException if the {@code next} method has not
     *         yet been called, or the {@code remove} method has already
     *         been called after the last call to the {@code next}
     *         method
     */
    default void remove() {
        throw new UnsupportedOperationException("remove");
    }

    /**
     * Performs the given action for each remaining element until all elements
     * have been processed or the action throws an exception.  Actions are
     * performed in the order of iteration, if that order is specified.
     * Exceptions thrown by the action are relayed to the caller.
     *
     * @implSpec
     * <p>The default implementation behaves as if:
     * <pre>{@code
     *     while (hasNext())
     *         action.accept(next());
     * }</pre>
     *
     * @param action The action to be performed for each element
     * @throws NullPointerException if the specified action is null
     * @since 1.8
     */
    default void forEachRemaining(Consumer<? super E> action) {
        Objects.requireNonNull(action);
        while (hasNext())
            action.accept(next());
    }
}

而今天我们经常面对遗留代码,这些代码暴露出枚举器接口,旦我们又希望在新的代码中只使用迭代器。这时候,我们就需要构造一个迭代器。

类图

这里写图片描述

代码实现
package adapter;

import java.util.Enumeration;
import java.util.Iterator;

/**
 * Created by ChongLou on 2017/8/19.
 */
public class EnumerationIterator implements Iterator {
    Enumeration enum1;

    public EnumerationIterator(Enumeration enum1) {
        this.enum1 = enum1;
    }

    public boolean hasNext() {
        return enum1.hasMoreElements();
    }

    public Object next() {
        return enum1.nextElement();
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }
}

总结

​ 适配器模式在生活中很常见,当我们没办法直接将内存卡插上电脑的时候,记得使用读卡器(适配器模式)哦。QAQ

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值