# 设计模式 第九章 迭代器模式、观察者模式、中介者模式
前言
迭代器模式、观察者模式、中介者模式
一、迭代器模式
1.介绍
行为型模式,提供一种遍历集合元素的统一接口,用一致的方法
遍历集合元素,不需要知道集合对象的底层表示。
2.代码示例
public interface Iterator<E> {
boolean hasNext();
E next();
}
private class Itr implements Iterator<E> {
int cursor;
int lastRet = -1;
int expectedModCount = modCount;
Itr() {}
public boolean hasNext() {
return cursor != size;
}
@SuppressWarnings("unchecked")
public E next() {
checkForComodification();
int i = cursor;
if (i >= size)
throw new NoSuchElementException();
Object[] elementData = ArrayList.this.elementData;
if (i >= elementData.length)
throw new ConcurrentModificationException();
cursor = i + 1;
return (E) elementData[lastRet = i];
}
}
public interface List<E> extends Collection<E> {
Iterator<E> iterator();
}
public class ArrayList<E> extends AbstractList<E>
implements List<E>, RandomAccess, Cloneable, java.io.Serializable
{
public Iterator<E> iterator() {
return new Itr();
}
}
二、观察者模式
1.介绍
当对象间存在一对多关系时,则使用观察者模式。比如,当一个
对象被修改时,则会自动通知依赖它的对象。
观察者模式属于行为型模式。
2.代码示例
public interface Observer {
void update(Observable o, Object arg);
}
public class Observable {
private boolean changed = false;
private Vector<Observer> obs;
public Observable() {
obs = new Vector<>();
}
public synchronized void addObserver(Observer o) {
if (o == null)
throw new NullPointerException();
if (!obs.contains(o)) {
obs.addElement(o);
}
}
public synchronized void deleteObserver(Observer o) {
obs.removeElement(o);
}
三、中介模式
1. 介绍
用一个中介对象来封装一系列的对象交互,中介者使各个对象不
需要显示地相互引用,从而解耦,而且可以独立改变他们之间
的交互。
2. 代码示例
public class ChatRoom {
public static void showMessage(User user, String message){
System.out.println(new Date().toString()
+ " [" + user.getName() +"] : " + message);
}
}
public class User {
private String name;
public void sendMessage(String message){
ChatRoom.showMessage(this,message);
}
}
public class Client{
public static void main(String[] args) {
User robert = new User("Robert");
User john = new User("John");
robert.sendMessage("Hi! John!");
john.sendMessage("Hello! Robert!");
}
}