Search code examples
javaobserver-patternobservable

Observable Pattern Implementation not calling update method


I am working to implement the Observable Design pattern on code that was provided for an assignment. I don't want the whole answer, but I do want to understand what is missing. I won't copy all of the code, but the pertinent pieces that I a have written so far. The code is a simple banking GUI that allows us to save Savings and Checking accounts to an ArrayList. My first step was to pull that out into a new object AccountList and extend Observable as such:

public class AccountList extends Observable {
public List<AAccount> accountList;

public AccountList(List<AAccount> accountList) {
    this.accountList = accountList;
}

public void add(AAccount acc) {
    accountList.add(acc);
    hasChanged();
    notifyObservers();
}
}

My next step was to implement an observer class as such:

public class AccountListObserver implements Observer{

public AccountListObserver(Observable o) {
    o.addObserver(this);
}

@Override
public void update(Observable o, Object arg) {
    System.out.println("Account " + o + " has been added, " +
            "there are now " + o + " accounts on the server.");

}
}

Now within the actual Server class I have the following called out in the beginning:

AccountList accList = new AccountList(new ArrayList<AAccount>());
Observer accObserver = new AccountListObserver(accList);

Then whenever an account is added I am calling accList.add(acc)

I am not getting my output but the program runs fine. What piece(s) am I missing to make this functional. Once I understand what is missing or needs to be moved/changed, I can make the necessary changes for all of the functions. I am just very confused by what could be missing because it seems like a logical configuration.


Solution

  • Replace call to hasChanged() with setChanged(). This sets the changed flag to true and allows notifyObservers() method to notify the observers.