首页 > 代码库 > Java设计模式(八)观察者模式 迭代器模式

Java设计模式(八)观察者模式 迭代器模式

(十五)观察者模式

观察者模式,定义对象间一对多关系,一个对象状态发生改变,所有依赖于它的对象都收到通知并且自动更新,观察者与被观察者分开。例如邮件订阅、RSS订阅,如果有更新就会邮件通知你。

interface Observers{
	public void update();
}
class Observer1 implements Observers{
	public void update(){
		System.out.println("observer1 has received");
	}
}
class Observer2 implements Observers{
	public void update(){
		System.out.println("observer2 has received");
	}
}
interface Subject {
	public void add(Observers ob);
	public void delete(Observers ob);
	public void notifyObservers();
	public void operation();
}
abstract class AbstractSubject implements Subject{
	private Vector<Observers> vector = new Vector<>();
	public void add(Observers ob){
		vector.add(ob);
	}
	public void delete(Observers ob){
		vector.remove(ob);
	}
	public void notifyObservers(){
		Enumeration<Observers> enumo = vector.elements();
		while(enumo.hasMoreElements()){
			enumo.nextElement().update();
		}
	}
}
class MySubject extends AbstractSubject{
	public void operation(){
		System.out.println("update self");
		notifyObservers();
	}
}
public class Observer {
	public static void main(String[] args){
		Subject sub = new MySubject();
		sub.add(new Observer1());
		sub.add(new Observer2());
		sub.operation();
	}
}
(十六)迭代器模式

说到迭代器首先想到 Iterator ,使用迭代器来为顺序访问集合元素提供一种方式。下面是自己的一个集合,当然只能放 int ,简单的实现了 迭代器的功能,当然实际的Java迭代器比这要复杂很多。

interface Collection{
	public Iterator iterator();
	public Object get(int i);
	public int size();
	public void add(int n);
}
interface Iterator{
	public Object previous();
	public Object next();
	public boolean hasNext();
	public Object first();
}
class MyCollection implements Collection{
	private int count = 10;
	private int[] num = new int[count];
	public void add(int n){
		for(int i = 0;i < num.length;i++){
			if(num[i] == 0){
				num[i] = n;
				return;
			}
		}
	}
	public MyCollection(int count){
		this.count = count;
	}
	@Override
	public Iterator iterator() {
		return new MyIterator(this);
	}
	@Override
	public Object get(int i) {
		return num[i];
	}
	@Override
	public int size() {
		return num.length;
	}
}
class MyIterator implements Iterator{
	private Collection collection;
	private int pos = -1;
	public MyIterator(Collection collection){
		this.collection = collection;
	}
	@Override
	public Object previous() {
		if(pos > 0){
			pos--;
		}
		return collection.get(pos);
	}
	@Override
	public Object next() {
		if(pos < collection.size() - 1){
			pos ++;
		}
		return collection.get(pos);
	}

	@Override
	public boolean hasNext() {
		if(pos < collection.size() - 1){
			return true;
		}else{
			return false;
		}
	}

	@Override
	public Object first() {
		pos = 0;
		return collection.get(pos);
	}
	
}
public class IteratorTest {
	public static void main(String[] args){
		Collection col = new MyCollection(10);
		for(int i = 0 ; i < 10;i++){
			col.add(i * 23);
		}
		Iterator it = col.iterator();
		while(it.hasNext()){
			System.out.println(it.next());
		}
	}
}