{"id":37853,"date":"2016-08-16T23:55:06","date_gmt":"2016-08-16T18:25:06","guid":{"rendered":"http:\/\/www.tothenew.com\/blog\/?p=37853"},"modified":"2016-08-19T10:53:01","modified_gmt":"2016-08-19T05:23:01","slug":"observer-design-pattern","status":"publish","type":"post","link":"https:\/\/www.tothenew.com\/blog\/observer-design-pattern\/","title":{"rendered":"Observer Design Pattern"},"content":{"rendered":"<p><b>Observer Design Pattern<\/b><\/p>\n<p>When <a title=\"java consulting services\" href=\"http:\/\/www.tothenew.com\/java-development-services-development-services\">we build applications<\/a> using object oriented paradigm, we try to develop each of our component independent of all other component that exist in our system. Although component independency fixes a lot of problem and it&#8217;s very convenient, but sometime it makes difficult to establish interaction between these independent component. So the problem is how we can make each of these component interact with each other.<\/p>\n<p><span style=\"font-weight: 400;\">The Observer Pattern helps us solve this problem because each class or component in our existing system can be notified about the state change of other component.The Observer Pattern is a kind of behavior pattern which is concerned with the assignment of responsibilities between objects.<\/span><\/p>\n<p>The Observer Pattern defines a one-to-many dependency between objects so that when one object changes its state, all its dependents \u00a0are notified and updated automatically. The\u00a0Observer pattern describes these dependencies. The key objects in this pattern are\u00a0subject and observer. A subject may have any number of dependent observers. All observers are notified whenever the subject undergoes a change in its state. In response, each observer will query the subject to synchronize its state with the subject state.<\/p>\n<p><i><span style=\"font-weight: 400;\">A better way to understand this pattern is through example.<\/span><\/i><\/p>\n<p>Let&#8217;s assume that we are working for a fantastic e-commerce site that has almost all kind of products and provide the latest information of the trends, new coupons, discount and other offers to its subscribed user. A user can subscribe to his\/her <a title=\"product engineering solutions\" href=\"http:\/\/www.tothenew.com\/product-engineering\">favorite product<\/a> (which may be currently out of stock) and get notification once the product is available in stock or the product is available at discount or when its price decreases.<\/p>\n<p>For easy understanding let&#8217;s see how to develop one of the above feature using observer design pattern.<\/p>\n<p><b>Requirement<\/b><\/p>\n<p>While visiting our ecommerce site, a customer found one product very interesting and he has a great desire to buy that product.Unfortunately that product is currently out of stock. To avoid the customer disappointment, there is an option available for the customer to get subscribed to that product. So once the product is available in stock, subscribed user can be notified for its availability.<\/p>\n<p>So here user is an observer who wants to observe the Product for its availability. In other words whenever the state of subject i.e product changes from &#8216;out of stock&#8217; to &#8216;in stock&#8217;, the observer (user) should be notified.<\/p>\n<p><span style=\"font-weight: 400;\">Here product(subject) and user(observer) are two separate component and want to interact with each other.<\/span><\/p>\n<p><b>Implementation<\/b><\/p>\n<p><span style=\"font-weight: 400;\">There are four participants in the Observer pattern: <\/span><\/p>\n<ul>\n<li style=\"font-weight: 400;\"><b><i>Subject<\/i><\/b><span style=\"font-weight: 400;\">, which is used to register observers. Objects use this interface to register as observers and also to remove themselves \u00a0from being observers.<\/span><\/li>\n<li style=\"font-weight: 400;\"><b><i>Observer<\/i><\/b><span style=\"font-weight: 400;\">, defines an updating interface for objects that should be notified of changes in a subject. All observers need to \u00a0implement the Observer interface. This interface has a method update(), which gets called when the Subject\u2019s state changes. <\/span><\/li>\n<li style=\"font-weight: 400;\"><b><i>ConcreteSubject<\/i><\/b><span style=\"font-weight: 400;\">, stores the state of interest to ConcreteObserver objects. It sends a notification to its observers when its state \u00a0changes. A concrete subject always implements the Subject interface. The notifyObservers() method is used to update \u00a0all the current observers whenever the state changes. <\/span><\/li>\n<li style=\"font-weight: 400;\"><b><i>ConcreteObserver<\/i><\/b><span style=\"font-weight: 400;\">, maintains a reference to a ConcreteSubject object and implements the Observer interface. Each observer \u00a0registers with a concrete subject to receive updates. \u00a0<\/span><\/li>\n<\/ul>\n<p><span style=\"font-weight: 400;\">Although we can define all the above mentioned participants our self but Java brings a lot to the table. There are already methods, classes and interfaces defined in <\/span><span style=\"font-weight: 400;\">java.util<\/span><span style=\"font-weight: 400;\"> package meant for easy implementation of this pattern. We can use these components of <\/span><span style=\"font-weight: 400;\">java.util<\/span><span style=\"font-weight: 400;\"> package and customise it as per our requirement.<\/span><\/p>\n<p><b>Following component are used from java.util package to implement this pattern:-<\/b><\/p>\n<ol>\n<li style=\"font-weight: 400;\"><b>public interface Observer- <\/b><span style=\"font-weight: 400;\">All observer needs to implement this interface to get notification about the state change of subject.<br \/>\n<\/span><strong>Note-<\/strong> In our case User is an observer so user class needs to implement this interface.<br \/>\nThis interface has one method- void update(Observable o, Object arg): This method is called whenever the observed object is changed. An application calls an Observable object&#8217;s notifyObservers() method to have all the object&#8217;s observers notified of the change.<\/li>\n<li style=\"font-weight: 400;\"><b>public class Observable- <\/b><span style=\"font-weight: 400;\">It is basically a subject to whom observer wants to observe. So it can be sub-classed to represent an object that the application wants to have observed.<br \/>\n<\/span><span style=\"line-height: 1.71429; font-size: 1rem;\">Note- In our case Product is a subject that needs to be observed. So Product class needs to be the sub-class of Observable class.<\/span><\/li>\n<\/ol>\n<p><b>Observable class has below useful methods-<\/b><\/p>\n<ol>\n<li style=\"font-weight: 400;\"><b>public synchronized void addObserver(Observer o)- <\/b><span style=\"font-weight: 400;\">Adds an observer to the set of observers for this object, provided that it is not the same as some observer already in the set.<br \/>\n<\/span><b>Note- <\/b><span style=\"font-weight: 400;\">The order in which notifications will be delivered to multiple observers is not specified.<\/span><\/li>\n<li style=\"font-weight: 400;\"><b>public synchronized void deleteObserver(Observer o)- <\/b><span style=\"font-weight: 400;\">Deletes an observer from the set of observers of this object. <\/span><\/li>\n<li style=\"font-weight: 400;\"><b>public synchronized void deleteObservers()- <\/b><span style=\"font-weight: 400;\">Clears the observer list so that this object no longer has any observers.<\/span><\/li>\n<li style=\"font-weight: 400;\"><b>public void notifyObservers()<\/b><\/li>\n<li style=\"font-weight: 400;\"><b>public void notifyObservers(Object arg) &#8211; <\/b><span style=\"font-weight: 400;\">If this object has changed, as indicated by the <\/span><b>hasChanged() <\/b><span style=\"font-weight: 400;\">method, then notify all of its observers and then call the clearChanged() method to indicate that this object has no longer changed.<br \/>\n<\/span><b style=\"line-height: 1.71429; font-size: 1rem;\">Note- <\/b><span style=\"font-weight: 400;\">Each observer has its update() method called with two arguments.<\/span><\/li>\n<li style=\"font-weight: 400;\"><b>protected synchronized void setChanged()- <\/b><span style=\"font-weight: 400;\">Marks this Observable object as having been changed; the hasChanged() method will now return true.<\/span><\/li>\n<li style=\"font-weight: 400;\"><b>protected synchronized void clearChanged()- <\/b><span style=\"font-weight: 400;\">Indicates that this object has no longer changed, or that it has already notified all of its observers of its most recent change. <\/span><\/li>\n<li style=\"font-weight: 400;\"><b>public synchronized boolean hasChanged()- <\/b><span style=\"font-weight: 400;\">Tests if this object has changed. <\/span><\/li>\n<li style=\"font-weight: 400;\"><b>public synchronized int countObservers()- <\/b><span style=\"font-weight: 400;\">Returns the number of observers of this Observable object. <\/span><\/li>\n<\/ol>\n<p><b>Sample Code of our use case<\/b><\/p>\n<p><b>Step 1:- Define Subject<\/b><\/p>\n<p><span style=\"font-weight: 400;\">For simplicity and better understanding we will be using &#8216;Observable&#8217; interface as Subject, provided in <\/span><span style=\"font-weight: 400;\">java.util<\/span><span style=\"font-weight: 400;\"> package meant for implementing observer design pattern. \u00a0<\/span><\/p>\n<p><b>Step 2:- Define Observer<\/b><\/p>\n<p><span style=\"font-weight: 400;\">We will be using &#8216;Observer&#8217; interface as provided in <\/span><span style=\"font-weight: 400;\">java.util<\/span><span style=\"font-weight: 400;\"> package. <\/span><\/p>\n<p><b>Step 3:- Define \u00a0<\/b><b>ConcreteSubject<br \/>\n<\/b><\/p>\n<p>[js]package com.intelligrape;<br \/>\nimport java.util.Observable;<br \/>\nimport java.util.Observer;<br \/>\npublic class Product extends Observable {<br \/>\nString productId;<br \/>\nString productName;<br \/>\nInteger stockQuantity;<br \/>\npublic Product(String productId, String productName, Integer stockQuantity) {<br \/>\nsuper();<br \/>\nthis.productId = productId;<br \/>\nthis.productName = productName;<br \/>\nthis.stockQuantity = stockQuantity;<br \/>\n}<br \/>\n\/\/ Getters and Setters of the field&#8230;<br \/>\npublic void setStockQuantity(Integer stockQuantity) {<br \/>\nthis.stockQuantity = stockQuantity;<br \/>\nSystem.out.println(&quot;Setting stock quantity of &quot; + this.toString());<br \/>\nif (this.stockQuantity &gt; 0) {<br \/>\n\/\/ Whenever stock quantity of current product is set to<br \/>\n\/\/ greater than zero, notify the subscribed user<br \/>\nthis.setChanged();<br \/>\nthis.notifyObservers();<br \/>\n}<br \/>\n}<br \/>\n@Override<br \/>\npublic String toString() {<br \/>\nreturn &quot;Product [productId=&quot; +productId + &quot;, productName=&quot; + productName<br \/>\n}<br \/>\n@Override<br \/>\npublic synchronized void addObserver(Observer o) {<br \/>\nSystem.out.println(&quot;Subscribing &quot; + o.toString() + &quot; for notification of &quot; + this.toString());<br \/>\nsuper.addObserver(o);<br \/>\n}<br \/>\n@Override<br \/>\npublic synchronized void deleteObserver(Observer o) {<br \/>\nSystem.out.println(&quot;Un-subscribing &quot;+ o.toString() + &quot; from notification of &quot; +<br \/>\nthis.toString());<br \/>\nsuper.deleteObserver(o);<br \/>\n}<br \/>\n@Override<br \/>\npublic void notifyObservers() {<br \/>\nSystem.out.println(&quot;Notifying observers for availability of &quot; + this.toString());<br \/>\nsuper.notifyObservers();<br \/>\n\/\/ if it requires to notify observer only for one time, then delete<br \/>\n\/\/ all the observers after notification by un-commenting below line.<br \/>\n\/\/ this.deleteObservers();<br \/>\n}<br \/>\n}[\/js]<\/p>\n<p><b>Step 4:- Define \u00a0ConcreteObserver<\/b><\/p>\n<p>[js]package com.intelligrape;<br \/>\nimport java.util.Observable;<br \/>\nimport java.util.Observer;<br \/>\npublic class User implements Observer {<br \/>\nString id;<br \/>\nString name;<br \/>\npublic User(String id, String name) {<br \/>\nsuper();<br \/>\nthis.id = id;<br \/>\nthis.name = name;<br \/>\n}<br \/>\n\/\/ Getters and Setters&#8230;<br \/>\n@Override<br \/>\npublic String toString() {<br \/>\nreturn &quot;User [id=&quot; + id + &quot;,name=&quot; + name + &quot;]&quot;;<br \/>\n}<br \/>\n@Override<br \/>\npublic void update(Observable o, Object arg) {<br \/>\nSystem.out.println(this.toString() + &quot; is notified successfully about the availability of &quot; + o.toString());<br \/>\n}<br \/>\n}[\/js]<\/p>\n<p><b>Define Main class<\/b><\/p>\n<p><span style=\"font-weight: 400;\">\u00a0<\/span><\/p>\n<p>[js]package com.intelligrape;<br \/>\npublic class Test {<br \/>\npublic static void main(String[] args) {<br \/>\nProduct product1 = new Product(&quot;P1&quot;,&quot;Jacket&quot;, 0);<br \/>\nProduct product2 = new Product(&quot;P2&quot;,&quot;Jeans&quot;, 5);<br \/>\nUser person1 = new User(&quot;customer 1&quot;,&quot;Ajay&quot;);<br \/>\nUser person2 = new User(&quot;customer 2&quot;,&quot;Saktiman&quot;);<br \/>\nUser person3 = new User(&quot;customer 3&quot;,&quot;Rajnikant&quot;);<br \/>\n\/\/ Adding observer for product1<br \/>\nproduct1.addObserver(person1);<br \/>\nproduct1.addObserver(person2);<br \/>\n\/\/ Setting stock quantity of product1 will notify all observer of product1<br \/>\nproduct1.setStockQuantity(8);<br \/>\n\/\/ Adding observer for product2<br \/>\nproduct2.addObserver(person1);<br \/>\nproduct2.addObserver(person2);<br \/>\nproduct2.addObserver(person3);<br \/>\nproduct2.setStockQuantity(0);<br \/>\n\/\/ Setting stock quantity of product2 will notify all observer of product2<br \/>\nproduct2.setStockQuantity(10);<br \/>\n\/\/ Removing person1 from observer list of product2<br \/>\n\/\/ Now person1 will not get notification about product2<br \/>\nproduct2.deleteObserver(person1);<br \/>\nproduct2.setStockQuantity(15);<br \/>\n}<br \/>\n}[\/js]<\/p>\n<p><b>Scope Of Further Improvement In Sample Code<\/b><\/p>\n<p>Instead of passing the entire subject, it is good to define a separate type and pass it as parameter to the handler method in the observer class. This type basically contains the meta information about the event. Eg source of event, time at which event was generated, what are the actual property of subject that leads to change in state of Subject etc. In our case subject domain is very small So we are not creating any separate type.<\/p>\n<p><b>Other Use Cases:-<\/b><\/p>\n<ol>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">Consider an e-commerce business. This pattern can be used in following scenario:- <\/span>\n<ol>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">An admin user can be notified with the increase in demand of given product. Whenever the number of subscribed user for a given product increases more than a given threshold then the admin user can be notified for the increase in demand for that product and that product can be marked as highly demanded product. <\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">Similarly whenever the quantity of highly demanded product falls below a given threshold then the admin user can be notified for that product. <\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">An admin user can associate a discount\/coupon with multiple product. So any change in discount\/coupon (eg change in discount percentage\/value or associating\/disassociating product to\/from coupon) must be notified to its associated product. So that the associated product can be updated with new available discount\/coupon.<\/span><\/li>\n<\/ol>\n<\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">Consider an excel sheet, data is shown to the user in different views. Generally data is shown in grid cells and as required different graphs, charts can be created for same data. Underlying data is same and when that data (subject) state changes all the different view (observer) are updated. <\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">The observer pattern is used in the model view controller (MVC) architectural pattern. In MVC this pattern is used to decouple the model from the view. View represents the Observer and the model is the Observable object.<br \/>\n<\/span><b style=\"line-height: 1.71429; font-size: 1rem;\">Example- <\/b><span style=\"font-weight: 400;\">Popular JSF technology also uses observer design pattern along with other design design pattern. The JSF framework implements the Observer pattern in UI components. JSF technology has two kinds of built-in events: ActionEvent and ValueChangedEvent. ActionEvent is useful in determining the activation of user interface components such as buttons. When a user clicks on the button, the JSF implementation notifies one or more action listeners added to the button. The button is activated or the state of the button (subject) changes. All listeners (or observers) are notified of the changes of state in subject that are added to the button. Similarly, when the value in the input UI component changes, the JSF implementation notifies ValueChangeListeners.<\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">A company can have many shareholders. So any change in policy of company needs to be notified to its shareholders. <\/span><\/li>\n<li style=\"font-weight: 400;\"><span style=\"font-weight: 400;\">A news agency gather news and publish them to different subscribers. \u00a0So when an event occurs, all the subscribers get notified. The solution need to be extensively enough to support new types of subscribers(maybe new communication technologies will appear). <\/span><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>Observer Design Pattern When we build applications using object oriented paradigm, we try to develop each of our component independent of all other component that exist in our system. Although component independency fixes a lot of problem and it&#8217;s very convenient, but sometime it makes difficult to establish interaction between these independent component. So the [&hellip;]<\/p>\n","protected":false},"author":270,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"iawp_total_views":9},"categories":[446,1],"tags":[],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/37853"}],"collection":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/users\/270"}],"replies":[{"embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/comments?post=37853"}],"version-history":[{"count":0,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/posts\/37853\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/media?parent=37853"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/categories?post=37853"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.tothenew.com\/blog\/wp-json\/wp\/v2\/tags?post=37853"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}