PRivate ArrayList list = new ArrayList(); private ArrayList observers = new ArrayList();
public void add( Integer i ) { list.add( i ); notifyObservers(); }
public Iterator iterator() { return list.iterator(); }
public Integer remove( int index ) { if( index < list.size() ) { Integer i = (Integer) list.remove( index ); notifyObservers(); return i; } return null; }
public void addObserver( Observer o ) { observers.add( o ); }
public void removeObserver( Observer o ) { observers.remove( o ); }
private void notifyObservers() { // loop through and notify each observer Iterator i = observers.iterator(); while( i.hasNext() ) { Observer o = ( Observer ) i.next(); o.update( this ); } } }
public IntegerAdder( IntegerDataBag bag ) { this.bag = bag; bag.addObserver( this ); }
public void update( Subject o ) { if( o == bag ) { System.out.println( "The contents of the IntegerDataBag have changed." ); int counter = 0; Iterator i = bag.iterator(); while( i.hasNext() ) { Integer integer = ( Integer ) i.next(); counter+=integer.intValue(); } System.out.println( "The new sum of the integers is: " + counter ); } }
}
import java.util.Iterator;
public class IntegerPrinter implements Observer {
private IntegerDataBag bag;
public IntegerPrinter( IntegerDataBag bag ) { this.bag = bag; bag.addObserver( this ); }
public void update( Subject o ) { if( o == bag ) { System.out.println( "The contents of the IntegerDataBag have changed." ); System.out.println( "The new contents of the IntegerDataBag contains:" ); Iterator i = bag.iterator(); while( i.hasNext() ) { System.out.println( i.next() ); } } }
IntegerAdder adder = new IntegerAdder( bag ); IntegerPrinter printer = new IntegerPrinter( bag );
// adder and printer add themselves to the bag
System.out.println( "About to add another integer to the bag:" ); bag.add( i9 ); System.out.println(""); System.out.println("About to remove an integer from the bag:"); bag.remove( 0 ); } }
运行main,你将看到:
c:javaworldjava Driver About to add another integer to the bag: The contents of the IntegerDataBag have changed. The new sum of the intergers is: 45 The contents of the IntegerDataBag have changed. The new contents of the IntegerDataBag contains: 1 2 3 4 5 6 7 8 9
About to remove an integer from the bag: The contents of the IntegerDataBag have changed. The new sum of the intergers is: 44 The contents of the IntegerDataBag have changed. The new contents of the IntegerDataBag contains: 2 3 4 5 6 7 8 9