Observer pattern
The Observer Pattern is a behavioral design pattern that establishes a one-to-many dependency between objects, where changes in one object (the subject or observable) trigger updates in other objects (observers) automatically. This pattern allows objects to communicate and stay synchronized without needing to be tightly coupled.
Rx observables & React useEffect
are good examples of this
An example below
In the below example, balance is rendered on a div that's not controlled
or rendered by any of the client components. But balance rendering inside
the div is still updated whenever there is a change on balance.
This is because balance div observes for changes on base BankAccount
instance changes & re-renders upon updates.
account.attachUpdateListener((x) => {
balanceEl.textContent = account.balance.toString();
});
}
Balance: 0
Google pay
PayTM
PhonePe
My Bank ATM
Other bank ATM
Bank branch
You can play around with an example in your console. You can access the
BankAccount through global BankAccount
- Let's create new handler for updates that logs all transactions.
-
Run
createBankAccount().attachUpdateListener(x => console.log(x))`
- Trigger some deposit & withdraw actions through buttons in UI & view the logs in console
References:
- Observer patternhttps://en.wikipedia.org/wiki/Observer_pattern
- Observer pattern detail from refacting guruhttps://refactoring.guru/design-patterns/observer
- Observer pattern info & implementation in Javahttps://www.tutorialspoint.com/design_pattern/observer_pattern.htm
- A nice Observer pattern example with cricket contexthttps://www.geeksforgeeks.org/observer-pattern-set-1-introduction/