JAVA JDK 1.1 提供了 Enumeration 接口,而在 1.2 中提供了 Iterator 接口,想要使用 1.2 的 JDK,则要将以前系统的 Enumeration 接口转化为 Iterator 接口,这时就需要适配器模式。
interface A {
void say();
}
class AImpl implements A {
@Override
public void say() {
System.out.println("我是中国人,我说中文");
}
}
interface B {
void play();
}
class A2BAdapter implements B {
private A a;
public A2BAdapter(A a) {
this.a = a;
}
@Override
public void play() {
a.say();
}
}
public class Main {
public static void main(String[] args) {
A a = new AImpl();
B b = new A2BAdapter(a);
b.play();
}
}
看下一下 spring是怎么装饰的 org.springframework.util.CollectionUtils.EnumerationIterator
/**
* Iterator wrapping an Enumeration.
*/
private static class EnumerationIterator<E> implements Iterator<E> {
private final Enumeration<E> enumeration;
public EnumerationIterator(Enumeration<E> enumeration) {
this.enumeration = enumeration;
}
@Override
public boolean hasNext() {
return this.enumeration.hasMoreElements();
}
@Override
public E next() {
return this.enumeration.nextElement();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Not supported");
}
}
再看下JDK java.util.Enumeration
default Iterator<E> asIterator() {
return new Iterator<>() {
@Override public boolean hasNext() {
return hasMoreElements();
}
@Override public E next() {
return nextElement();
}
};
}
评论