DESIGN PATTENS - OBSERVER PATTERN By, Srinivas Reddy.S www.JAVA9S.com
A Simple Requirement Display Boards Websites www.JAVA9S.com Mobile apps
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., www.JAVA9S.com
stockPricesChanged() StockUpdate getStockPrices() stockPricesChanged() observable MobileDisplay Update( ) observers StockBoardDisplay Update( ) WebDisplay Update( ) www.JAVA9S.com
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 www.JAVA9S.com
Stock Update StockBoard One to Many Relationship Mobile WEBSITE OTHER www.JAVA9S.com
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. www.JAVA9S.com
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 www.JAVA9S.com
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 www.JAVA9S.com
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 www.JAVA9S.com
Code – Example www.JAVA9S.com
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 www.JAVA9S.com
Object Oriented Principles applied Loose coupling between the Observer and Observable. Programming to Interfaces. Examples of Observer Pattern Swing event listeners Java RMI www.JAVA9S.com
Thank you Thank you www.JAVA9S.com JAVA9S @java9s Pages - Java9s.com