对于比较简单的遍历 (像数组或者有序列表),使用迭代器方式遍历较为繁琐,大家可能都有感觉,像 ArrayList,我们宁可愿意使用 for 循环和 get 方法来遍历集合。
总的来说:迭代器模式是与集合共生共死的,一般来说,我们只要实现一个集合,就需要同时提供这个集合的迭代器,就像 Java 中的 Collection,List、Set、Map 等,这些集合都有自己的迭代器。假如我们要实现一个这样的新的容器,当然也需要引入迭代器模式,给我们的容器实现一个迭代器。
4.2 ArrayList 中的迭代器模式
迭代器接口:
public interface Iterator<E> {
boolean hasNext();
E next();
default void remove() {
throw new UnsupportedOperationException("remove");
}
default void forEachRemaining(Consumer<? super E> action) {
Objects.requireNonNull(action);
while (hasNext())
action.accept(next());
}
}
ArrayList 的 Iterator:
public Iterator<E> iterator() {
return listIterator();
}
public ListIterator<E> listIterator(final int index) {
return new ListIterator<E>() {
public boolean hasNext() {
// ...
}
@SuppressWarnings("unchecked")
public E next() {
// ...
}
public boolean hasPrevious() {
// ...
}
@SuppressWarnings("unchecked")
public E previous() {
// ...
}
@SuppressWarnings("unchecked")
public void forEachRemaining(Consumer<? super E> consumer) {
// ...
}
public int nextIndex() {
// ...
}
public int previousIndex() {
// ...
}
public void remove() {
// ...
}
public void set(E e) {
// ...
}
public void add(E e) {
// ...
}
};
}
5. 责任链模式的简介和应用
5.1 简介
顾名思义,责任链模式 (Chain of Responsibility Pattern) 为请求创建了一个接收者对象的链。这种模式给予请求的类型,对请求的发送者和接收者进行解耦。这种类型的设计模式属于行为型模式,在这种模式中,通常每个接收者都包含对另一个接收者的引用。如果一个对象不能处理该请求,那么它会把相同的请求传给下一个接收者,依此类推。
5.2 demo
模拟一个村、镇、县的责任链关系请求。
protected abstract class Handler {
protected Handler next;
public abstract void handleRequest(String value);
public Handler next() {
return this.next;
}
public void setNext(Handler next) {
this.next = next;
}
}
private final class VillageHandler extends Handler {
@Override
public void handleRequest(String value) {
if ("village".equals(value)) {
System.out.println("VillageHandler: handled~");
} else {
System.out.println("VillageHandler: pass~");
this.next.handleRequest(value);
}
}
}
private final class TownHandler extends Handler {
@Override
public void handleRequest(String value) {
if ("town".equals(value)) {
System.out.println("VillageHandler: handled~");
} else {
System.out.println("Town: pass~");
this.next.handleRequest(value);
}
}
}
private final class CountyHandler extends Handler {
@Override
public void handleRequest(String value) {
if ("county".equals(value)) {
System.out.println("County: handled~");
} else if (this.next == null) {
System.out.println("no next Handler, this request can not be handle~");
} else {
System.out.println("County: pass~");
this.next.handleRequest(value);
}
}
}
public static void main(String[] args) {
TestBehaviorDesignModel model = new TestBehaviorDesignModel();
Handler villageHandler = model.new VillageHandler();
Handler townHandler = model.new TownHandler();
Handler countyHandler = model.new CountyHandler();