    01: import java.util.*;
    02: import javax.swing.event.*;
    03:
    04: /**
    05:    An invoice for a sale, consisting of line items.
    06: */
    07: public class Invoice
    08: {
    09:    /**
    10:       Constructs a blank invoice.
    11:    */
    12:    public Invoice()
    13:    {
    14:       items = new ArrayList();
    15:       listeners = new ArrayList();
    16:    }
    17:
    18:   /**
    19:       Adds an item to the invoice.
    20:       @param item the item to add
    21:    */
    22:    public void addItem(LineItem item)
    23:    {
    24:       items.add(item);
    25:       // notify all observers of the change to the invoice
    26:       ChangeEvent event = new ChangeEvent(this);
    27:       for (int i = 0; i < listeners.size(); i++)
    28:       {
    29:          ChangeListener listener
    30:             = (ChangeListener) listeners.get(i);
    31:          listener.stateChanged(event);
    32:       }
    33:    }
    34:
    35:    /**
    36:       Adds a change listener to the invoice.
    37:       @param listener the change listener to add
    38:    */
    39:    public void addChangeListener(ChangeListener listener)
    40:    {
    41:       listeners.add(listener);
    42:    }
    43:
    44:    /**
    45:       Gets an iterator that iterates through the items.
    46:       @return an iterator for the items
    47:    */
    48:    public Iterator getItems()
    49:    {
    50:       return new
    51:          Iterator()
    52:          {
    53:             public boolean hasNext()
    54:             {
    55:                return current < items.size();
    56:             }
    57:             public Object next()
    58:             {
    59:                Object r = items.get(current);
    60:                current++;
    61:                return r;
    62:             }
    63:             public void remove()
    64:             {
    65:                throw new UnsupportedOperationException();
    66:             }
    67:             private int current = 0;
    68:          };
    69:    }
    70:
    71:    public String format(InvoiceFormatter formatter)
    72:    {
    73:       String r = formatter.formatHeader();
    74:       Iterator iter = getItems();
    75:       while (iter.hasNext())
    76:       {
    77:          LineItem item = (LineItem) iter.next();
    78:          r += formatter.formatLineItem(item);
    79:       }
    80:       return r + formatter.formatFooter();
    81:    }
    82:
    83:    private ArrayList items;
    84:    private ArrayList listeners;
    85: }