001package horstmann.ch05_invoice;
002import java.util.ArrayList;
003import java.util.Iterator;
004
005import javax.swing.event.ChangeEvent;
006import javax.swing.event.ChangeListener;
007
008/**
009   An invoice for a sale, consisting of line items.
010 */
011public class Invoice
012{
013        /**
014      Constructs a blank invoice.
015         */
016        public Invoice()
017        {
018                items = new ArrayList<LineItem>();
019                listeners = new ArrayList<ChangeListener>();
020        }
021
022        /**
023      Adds an item to the invoice.
024      @param item the item to add
025         */
026        public void addItem(LineItem item)
027        {
028                items.add(item);
029                // Notify all observers of the change to the invoice
030                ChangeEvent event = new ChangeEvent(this);
031                for (ChangeListener listener : listeners)
032                        listener.stateChanged(event);
033        }
034
035        /**
036      Adds a change listener to the invoice.
037      @param listener the change listener to add
038         */
039        public void addChangeListener(ChangeListener listener)
040        {
041                listeners.add(listener);
042        }
043
044        /**
045      Gets an iterator that iterates through the items.
046      @return an iterator for the items
047         */
048        public Iterator<LineItem> getItems()
049        {
050                return new
051                                Iterator<LineItem>()
052                {
053                        public boolean hasNext()
054                        {
055                                return current < items.size();
056                        }
057
058                        public LineItem next()
059                        {
060                                return items.get(current++);
061                        }
062
063                        public void remove()
064                        {
065                                throw new UnsupportedOperationException();
066                        }
067
068                        private int current = 0;
069                };
070        }
071
072        public String format(InvoiceFormatter formatter)
073        {
074                String r = formatter.formatHeader();
075                Iterator<LineItem>iter = getItems();
076                while (iter.hasNext())
077                        r += formatter.formatLineItem(iter.next());
078                return r + formatter.formatFooter();
079        }
080
081        private ArrayList<LineItem> items;
082        private ArrayList<ChangeListener> listeners;
083}