hi guys, I've come across observers while working ona very very large project, and I didn't quite understand how they were structured and I suppose this had something to do with the huge size of the project itself.
Anyway, I then decided to delve a little more into that, I had a look in a few places, believe I understand more or less the theory and wrote some code - well in fact it's code that I got from a few places, play with it a little bit and then pretty much re wrote it again..
So, to my question now: could someone cast an eye on it and:
1)let me know if it makes sense (it works as expected
2)is that it? Does it, although very simplistically, represent the meaning and purpose of what the observer pattern is meant to be used for?
3)any suggestiong as to it can be improverd, expanded etc
The code is pretty simple, there is a bankAccount object - the Observable - and then I created a few Observers using a loop - the number is fixed to 7 in my example. The test class creates the Observable objects passing the Observable as a parameter to it, then it adds the observers to the list of observers and changes the Observable triggering the update method. that's it.
Here is the code:
//the observable
import java.util.Observable;
public class BankAccount extends Observable
{
private int balance = 0;
public BankAccount(int balance)
{
this.balance = balance;
}
public int getBalance()
{
return balance;
}
public void setBalance(int balance)
{
this.balance = balance;
setChanged();//set the flag to indicate that this observable has changed
notifyObservers();//notify everyone
}
}
//the Testing class
import java.util.ArrayList;
import java.util.Observer;
public class TestObserver
{
public static void main(String[] args)
{
ArrayList<Observer> users = new ArrayList<>();
BankAccount bankAccount = new BankAccount(1);
int observerNum = 7;
for(int i = 0; i < observerNum; i++){
BankAccountObserver bankAccountObserver = new BankAccountObserver(bankAccount);
users.add(bankAccountObserver);
}
for(Observer user : users){
bankAccount.addObserver(user);
}
bankAccount.setBalance(22);
}
}
//the Observer(s)
import java.util.Observable;
import java.util.Observer;
public class BankAccountObserver implements Observer
{
private BankAccount bankAccount = null;
public BankAccountObserver(BankAccount bankAccount)
{
this.bankAccount = bankAccount;
}
@Override
public void update(Observable o, Object arg)
{
if (o == bankAccount)
{
System.out.println("BankAccountObserver balance: " + bankAccount.getBalance());
}
}
}