<p><strong>The observer pattern</strong> is one of <strong><a href="https://dineshonjava.com/behavioral-design-pattern/">the behavioral patterns</a></strong>. The observer pattern defines an object which is called, subject. The subject object is responsible for maintaining a list of the objects, which depend on it. These objects are known as observers. Whenever a change of state occurs in a system, the subject object notifies observers about it. To notify the observers, the subject object calls one of their methods.</p>
<p>This pattern is used in implementing a distributed event handling systems, mostly in, event-driven software. The modern languages like C# and Java, they have built-in event constructs. These built-in features help in implementing the observer pattern components. The advantage of that is ease of programming and implementation of short codes. In modern-view-controller (MVC) architectural pattern, the observer pattern is a key part. In various different programming libraries and systems, the observer pattern is implemented.</p>
<h2>Observer Pattern</h2>
<div style="text-align: left;">
<blockquote><p><strong>According to the Gang of Four:</strong></p>
<div style="text-align: left;">Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically.</div>
</blockquote>
</div>
<p><strong>For example,</strong> facebook post comments is one of the example of the observer design pattern, if comment to the post of your friend, then you always notified by this post whenever any comment on same post again. The Figure below illustrates the Observer pattern.</p>
<p><img class="aligncenter wp-image-3304 size-full" src="https://dineshonjava.com/wp-content/uploads/2017/12/Observer.png" alt="Observer Design Pattern" width="663" height="329" /></p>
<p>To design, versatile and reusable object-oriented software, there is <strong><a href="https://dineshonjava.com/design-patterns_25/">23 well-known Gang of Four (GoF) design patterns</a></strong>, the observer pattern is one of them. There are several problems that the observer pattern cater. The need is to define a one-to-many dependency between object without having to make the objects tightly linked or coupled. To ensure that when an object in the system changes its state, the other objects, which are dependent, are notified automatically.</p>
<p>One of the dependent objects is supposed to be able to update an open-ended number of different other objects. To define a one-to-many dependency between objects using one single, defined object (subject- which is responsible to notify others the state of dependent objects directly), it creates inflexibility, because it tightly couples the subject object to certain dependent objects. The objects which are tightly linked together, it is difficult to implement, test, change and reuse them, because these objects hold information about and know how to update many different objects, which are linked to it. The observer pattern defines the Subject and Observer objects because the observer pattern is used to automatically notify other dependent objects about the change in state of the subject object.</p>
<div style="background-color: #f2f9fc; border-radius: 3px; border: 1px solid #c9e6f2; line-height: 1.45; padding: 16px 16px 16px 16px;">
<h2 dir="ltr">Spring 5 Design Pattern Book</h2>
<div dir="ltr" style="color: #20124d; font-family: 'calibri' , sans-serif; font-size: 13pt; text-align: justify;">You could purchase my <strong>Spring 5 book</strong> that is with title name &#8220;<strong>Spring 5 Design Patterns</strong>&#8220;. This book is available on the <a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?ie=UTF8&;qid=1507925340&;sr=8-1&;keywords=spring+5+design+pattern" target="_blank" rel="noopener"><strong>Amazon</strong></a> and <a href="https://www.packtpub.com/application-development/spring-5-design-patterns" target="_blank" rel="noopener"><strong>Packt</strong></a> publisher website. Learn various <strong>design patterns</strong> and <strong>best practices</strong> in Spring 5 and use them to solve common design problems. You could use author discount to purchase this book by using code- &#8220;<strong>AUTHDIS40</strong>&#8220;.</div>
<div dir="ltr"></div>
<div dir="ltr"><a href="https://www.amazon.in/Spring-Design-Patterns-Dinesh-Rajput/dp/1788299450/ref=sr_1_1?s=books&;ie=UTF8&;qid=1512607966&;sr=1-1&;keywords=dinesh+rajput" target="_blank" rel="noopener"><img class="aligncenter wp-image-3053 size-medium" title="Spring-5-Design-Pattern" src="https://dineshonjava.com/wp-content/uploads/2013/03/Spring-5-design-pattern-243x300.jpg" width="243" height="300" /></a></div>
</div>
<p>The subject is responsible for maintaining a list of Observers and notifying them about the state changes by calling update() function. The observers are responsible for registering and unregistering themselves on the subject object. This is done to be able to get notified when a change of state occurs, and to be able to update their state when they are notified. With this approach, the subject and observers are now loosely coupled. They have no direct information of a link to each other. It is now possible to add or remove the observers independently.</p>
<p>The notification-registration communication is also known as publish-subscribe. The problem is observer behavioral pattern is that is able to cause memory leaks, which is also called, lapsed listener problem. This occurs because in the observer pattern’s basic implementation, the explicit registration and deregistration, both are required because of the subject object stores a strong reference to the observers, which keep them running. The memory leaks can be prevented from happening, if the references, stored in the subject change to weak references.</p>
<div style="text-align: left;">
<blockquote><p><strong>also read:</strong></p>
<ul style="text-align: left;">
<li><a title="https://dineshonjava.com/chain-responsibility-pattern/" href="https://dineshonjava.com/chain-responsibility-pattern/">Chain of responsibility Pattern</a></li>
<li><a title="https://dineshonjava.com/command-pattern-design-patterns-java/" href="https://dineshonjava.com/command-pattern-design-patterns-java/">Command Design Pattern</a></li>
<li><a title="https://dineshonjava.com/strategy-pattern-design-patterns-java/" href="https://dineshonjava.com/strategy-pattern-design-patterns-java/">Strategy Design Pattern</a></li>
<li><a title="https://dineshonjava.com/template-method-pattern-design-java/" href="https://dineshonjava.com/template-method-pattern-design-java/">Template method Design Pattern</a></li>
<li><a title="https://dineshonjava.com/interpreter-pattern-design-patterns-java/" href="https://dineshonjava.com/interpreter-pattern-design-patterns-java/">Interpreter Design Pattern</a></li>
<li><a title="https://dineshonjava.com/iterator-pattern-design-patterns-java/" href="https://dineshonjava.com/iterator-pattern-design-patterns-java/">Iterator Design Pattern</a></li>
<li><a title="https://dineshonjava.com/mediator-pattern-design-patterns-java/" href="https://dineshonjava.com/mediator-pattern-design-patterns-java/">Mediator Design Pattern</a></li>
<li><a title="https://dineshonjava.com/memento-pattern-design-patterns-java/" href="https://dineshonjava.com/memento-pattern-design-patterns-java/">Memento Design Pattern</a></li>
<li><a title="https://dineshonjava.com/creational-design-patterns/" href="https://dineshonjava.com/creational-design-patterns//">Creational GoF Design Patterns</a></li>
<li><a title="https://dineshonjava.com/structural-design-patterns/" href="https://dineshonjava.com/structural-design-patterns/">Structural GoF Design Patterns</a></li>
</ul>
</blockquote>
</div>
<h2>Benefits of the Observer Pattern</h2>
<p>There are following lists of the benefits of using the Observer pattern:</p>
<ul>
<li>This pattern provides decoupled relationship between the subject and observer</li>
<li>It provides support for broadcasting.</li>
</ul>
<h2>UML Class Diagram for This Pattern</h2>
<p>Let&#8217;s see the following UML diagram is showing the all components of Observer design pattern:</p>
<p><img class="aligncenter wp-image-3305 size-full" src="https://dineshonjava.com/wp-content/uploads/2017/12/observer.gif" alt="Observer Pattern Design Patterns in Java" width="414" height="308" /><br />
<strong>Subject</strong><br />
It is an interface. It knows its observers.<br />
<strong>ConcreteSubject</strong><br />
It is a concrete implementation of Subject, it has information about all its observers to be notifed when its state changes.<br />
<strong>Observer</strong><br />
It is an interfac to be notified of changes in a subject.<br />
<strong>ConcreteObserver</strong><br />
It is a concrete implementation of Observer, it keep its state consistent with the subject&#8217;s state.</p>
<h2>Observer Pattern Implementation Example</h2>
<p>Observer design pattern is also called as publish-subscribe pattern. Some of it’s implementations are;</p>
<ul>
<li>java.util.EventListener in Swing</li>
<li>javax.servlet.http.HttpSessionBindingListener</li>
<li>javax.servlet.http.HttpSessionAttributeListener</li>
</ul>
<h3>Step 1: Create Subject.<br />
Subject.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.dineshonjava.observer.pattern; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public interface Subject { 
	 
	//methods to register user as an facebook friend observers 
	public void registerAsAFriend(Observer friendRequest); 
	 
	//methods to unregister user from facebook friend observers 
	public void unregisterFromFriend(Observer removeFriend); 
	 
	//method to notify observers i.e. facebook friends of change 
	public void notifyFacebookFriends(); 
	 
	//method to get updates from subject 
	public Object getUpdate(Observer obj); 
	 
} 
 
</pre>
<h3>Step 2: Create Observer.<br />
Observer.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.dineshonjava.observer.pattern; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public interface Observer { 
	 
	public void update(); 
		 
	public void setSubject(Subject sub); 
} 
 
</pre>
<h3>Step 3: Create concrete subject class.<br />
FacebookPost.java</h3>
<pre class="highlight">package com.dineshonjava.observer.pattern; 
 
import java.util.ArrayList; 
import java.util.List; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class FacebookPost implements Subject { 
	 
	private List observers = new ArrayList(); 
	private String comment; 
 
	@Override 
	public void registerAsAFriend(Observer friendRequest) { 
		observers.add(friendRequest);	 
	} 
 
	@Override 
	public void unregisterFromFriend(Observer removeFriend) { 
		observers.remove(removeFriend);	 
	} 
 
	@Override 
	public void notifyFacebookFriends() { 
		for (Observer observer : observers) { 
			observer.update(); 
		} 
	} 
 
	@Override 
	public Object getUpdate(Observer obj) { 
		return this.comment; 
	} 
	 
	//method to post message to the topic 
	public void postComment(String comment){ 
		System.out.println("Comment Posted to Post: "+comment); 
		this.comment=comment; 
		notifyFacebookFriends(); 
	} 
 
} 
 
</pre>
<h3>Step 4: Create concrete observer class.<br />
FacebookPost.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.dineshonjava.observer.pattern; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class FacebookFriend implements Observer { 
	 
	private String friendName; 
	private Subject facebookPost; 
	 
	public FacebookFriend(String friendName){ 
		this.friendName = friendName; 
	} 
 
	@Override 
	public void update() { 
		String comment = (String) facebookPost.getUpdate(this); 
		if(comment == null){ 
			System.out.println(friendName+":: No new comment"); 
		}else{ 
			System.out.println(friendName+":: New comment::"+comment); 
		} 
	} 
 
	@Override 
	public void setSubject(Subject facebookPost) { 
		this.facebookPost = facebookPost; 
	} 
 
} 
 
</pre>
<h3>Step 5: Use Subject and concrete observer objects.<br />
ObserverPatternDemo.java</h3>
<pre class="highlight">/** 
 * 
 */ 
package com.dineshonjava.observer.pattern; 
 
/** 
 * @author Dinesh.Rajput 
 * 
 */ 
public class ObserverPatternDemo { 
 
	/** 
	 * @param args 
	 */ 
	public static void main(String[] args) { 
		//create a facebook post i.e. a subject 
		FacebookPost facebookPost = new FacebookPost(); 
				 
		//create facebook friends i.e. observers 
		Observer dinesh = new FacebookFriend("Dinesh"); 
		Observer arnav = new FacebookFriend("Arnav"); 
		Observer anamika = new FacebookFriend("Anamika"); 
				 
		//register facebook friends i.e. observers to the facebook post or friend list i.e. subject 
		facebookPost.registerAsAFriend(dinesh); 
		facebookPost.registerAsAFriend(arnav); 
		facebookPost.registerAsAFriend(anamika); 
				 
		//tag your friends to the facebook post i.e. observer to subject 
		dinesh.setSubject(facebookPost); 
		arnav.setSubject(facebookPost); 
		anamika.setSubject(facebookPost); 
				 
		//check if any update is available 
		arnav.update(); 
				 
		//new comment added to the facebook post i.e. to subject 
		facebookPost.postComment("Hello Observers!!! How are you!!!"); 
	} 
 
} 
 
</pre>
<h3>Step 5: Let&#8217;s run the demo class and verify the output.</h3>
<pre class="highlight">Arnav:: No new comment 
Comment Posted to Post: Hello Observers!!! How are you!!! 
Dinesh:: New comment::Hello Observers!!! How are you!!! 
Arnav:: New comment::Hello Observers!!! How are you!!! 
Anamika:: New comment::Hello Observers!!! How are you!!! 
 
</pre>
<div class="wp-post-navigation"> 
									 <div class="wp-post-navigation-pre"> 
									 <a href="https://dineshonjava.com/mediator-pattern-design-patterns-java/">Previous</a> 
									 </div> 
									 <div class="wp-post-navigation-next"> 
									 <a href="https://dineshonjava.com/state-pattern/">Next</a> 
									 </div> 
									</div>
<script type="text/javascript">
jQuery(document).ready(function($) {
 $.post('https://dineshonjava.com/wp-admin/admin-ajax.php', {action: 'mts_view_count', id: '3303'});
});
</script>
Strategy Design Patterns We can easily create a strategy design pattern using lambda. To implement…
Decorator Pattern A decorator pattern allows a user to add new functionality to an existing…
Delegating pattern In software engineering, the delegation pattern is an object-oriented design pattern that allows…
Technology has emerged a lot in the last decade, and now we have artificial intelligence;…
Managing a database is becoming increasingly complex now due to the vast amount of data…
Overview In this article, we will explore Spring Scheduler how we could use it by…