Java Observer

That wasn't too painful, but now let's consider the same approach in Java. In Java, there is direct language support for the observer. In order to provide a similar solution in Java, we simply implement the observer interface in the class that is to be notified. The observable class can be used to provide the framework for handling the registration and notification of observers. Notice how much more straight-forward this is when the framework is in place. To avoid turning this example into a Java primer, I've avoided doing the GUI in Java (which, unfortunately, is something much more straightforward in Visual Basic than in Java).

Account

package JavaObserver;
import java.util.*;

public class Account extends Observable
{

    public void addEntry(Date entryDate, double amount)
    {
        AccountEntry ae = new AccountEntry(entryDate, amount);
        m_entries.addElement(ae);
        setChanged();
    }

    public Enumeration getEntries()
    {
        return m_entries.elements();
    }

    private Vector m_entries;

}

AccountEntry

package JavaObserver;
import java.util.Date;

public class AccountEntry
{
    AccountEntry(Date entryDate, double amount)
    {
        m_entryDate = entryDate;
        m_amount = amount;
    }

    public Date getEntryDate()
    {
        return m_entryDate;
    }

    public double getAmount()
    {
        return m_amount;
    }

    private Date m_entryDate;
    private double m_amount;
}

AccountObserver

package JavaObserver;
import java.util.*;
public class AccountObserver implements Observer
{
    public AccountObserver(Account account)
    {
        m_account = account;
        m_account.addObserver(this);
    }

    public void sync()
    {
        m_account.notifyObservers();
    }

    public void update(Observable observer, Object unused)
    {
        Account acct = (Account)observer;
        for(Enumeration e = acct.getEntries(); e.hasMoreElements();)
        {
              AccountEntry entry = (AccountEntry)e.nextElement();

              System.out.println(entry.getEntryDate().toString() +
":" + (new Double(entry.getAmount())).toString());
        }
    }
    private Account m_account;
}

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.79.241