This pattern is used in publisher-consumer kind of situations
This pattern is used where a change in data which is observable by one or many observers,The pattern is such that no matter what kind of Observers ATMObserver , OnlineAcObsever) come the Observable or the subject(BankAccount) has no impact.So tomorrow if there is a need to add MobileObserver for BankAccount, that can just be added without any changes and implementing AccountObserver.
The Subject or Observable concrete class,in this case a bank account which is observable.The Observers OnlineACObserver ATMACObserver register with this class and get updates about the bank account.
public class BankAccount implements SubjectObservable {
public ArrayList observers = new ArrayList();
String balance;
String account;
public void deregisterObserver(AccountObserver o) {
observers.remove(observers.indexOf(o));
}
public void notifyObservers() {
for (int i = 0; i < this.observers.size(); i++) {
AccountObserver observer = (AccountObserver) this.observers.get(i);
observer.update("ACCOUNTNUM", "BALANCE < 200");
}
}
public void registerObserver(AccountObserver o) {
observers.add(o);
}
public void setBalance(String balance) {
this.balance = balance;
this.notifyObservers();
}
The Concrete implementation of Observer take the case of ATMACObserver this observer registers with the BankAccount and gets invoked by the Subject when there is a change or update in the Subject.
public class ATMObserver implements AccountObserver {
String message;
SubjectObservable bankAccount;
public ATMObserver(SubjectObservable bankAccount) {
this.bankAccount = bankAccount;
this.bankAccount.registerObserver(this);
}
public void update(String accountNumber, String balance) {
{
this.message = "welcome to ATM " + accountNumber + " " + balance;
}
}
The client code can be as follows.
class Client {
public static void main(String[] args) {
// creating observable Bank Account
SubjectObservable bankAccount = new BankAccount();
// Observer 1 onlin
OnlineAcObserver online = new OnlineAcObserver(bankAccount);
// Observer 2 ATM
ATMObserver atm = new ATMObserver(bankAccount);
//update account values which updates the observer
online.getMessage();