Download presentation
1
DESIGN PATTENS - OBSERVER PATTERN
By, Srinivas Reddy.S
2
A Simple Requirement Display Boards Websites www.JAVA9S.com
Mobile apps
3
A Simple Requirement.. Stock Market
An application in the server monitors and gathers information related to Stock prices. The changed stock prices should be informed to different parties like stock market display boards, mobile apps, websites etc.,
4
stockPricesChanged()
StockUpdate getStockPrices() stockPricesChanged() observable MobileDisplay Update( ) observers StockBoardDisplay Update( ) WebDisplay Update( )
5
stockPricesChanged()
mobileDisplay.update(stockUpdates); stockBoardDisplay.update(stockUpdates); webdisplay.update(stockUpdates); } What if there are few more observers to be added? Violates the OO principles – Less dependency Less number of changes
6
Stock Update StockBoard One to Many Relationship Mobile WEBSITE OTHER
7
OBSERVER PATTERN OBSERVER PATTERN defines one to many relationship between the objects. When the state of the Observable object changes, all the observers will notified and updated automatically.
8
Design – Observer pattern
Collection of Observers <<interface>> Observable registerObserver() removeObserver() notifyObservers() <<interface>> Observer update() ObservableImplementation registerObserver(){...} removeObserver(){...} notifyObservers(){....} ObserverImplementation update(){...} //Other methods of observer Instance variable
9
Design – Observer pattern - example
<<interface>> Observable registerObserver() removeObserver() notifyObservers() <<interface>> Observer update() <<interface>> Display display() StockUpdate registerObserver(){...} removeObserver(){...} notifyObservers(){....} MobileDisplay update(){...} //Other methods of observer
10
Pull and Push model Stock Update Push model StockBoard Pull model
Update(Observable o, Map stocks) StockBoard Pull model update() *The observer should have a reference to Observable
11
Code – Example
12
Java's build in Observer pattern
java.util.Observable java.util.Observer A concrete class An Interface Issues: Observable is a concrete class and due to which the class which has the state will not have a chance to have inheritance of its own. Well know usage: Java Swing Java RMI
13
Object Oriented Principles applied
Loose coupling between the Observer and Observable. Programming to Interfaces. Examples of Observer Pattern Swing event listeners Java RMI
14
Thank you Thank you www.JAVA9S.com JAVA9S @java9s Pages - Java9s.com
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.