180 likes | 336 Views
DESIGN PATTENS - OBSERVER PATTERN. By, Srinivas Reddy.S. www.JAVA9S.com. A Simple Requirement. Display Boards. Websites. Mobile apps. www.JAVA9S.com. A Simple Requirement. Stock Market An application in the server monitors and gathers information related to Stock prices.
E N D
DESIGN PATTENS- OBSERVER PATTERN By, SrinivasReddy.S www.JAVA9S.com
A Simple Requirement Display Boards Websites Mobile apps www.JAVA9S.com
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
observable observers www.JAVA9S.com
stockPricesChanged() 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
StockBoard Mobile Stock Update WEBSITE OTHER One to Many Relationship 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 Instance variable www.JAVA9S.com
Design – Observer pattern - example www.JAVA9S.com
Pull and Push model Stock Update Push 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 Pages - Java9s.com JAVA9S www.JAVA9S.com