Observer Design Pattern Tutorial

Observer Design Pattern TutorialWelcome to my Observer Design Pattern Tutorial. I cover a lot in this tutorial including the Observer pattern, how to use it with threads and much more.

The Observer pattern is a software design pattern in which an object, called the subject (Publisher), maintains a list of its dependents, called observers (Subscribers), and notifies them automatically of any state changes, usually by calling one ofΒ their methods.

All of the code follows the video to help you learn.

If you like videos like this, please tell Google

Sharing is nice

Code & Comments from the Video

SUBJECT.JAVA

// This interface handles adding, deleting and updating
// all observers 

public interface Subject {
	
	public void register(Observer o);
	public void unregister(Observer o);
	public void notifyObserver();
	
}

OBSERVER.JAVA

// The Observers update method is called when the Subject changes

public interface Observer {
	
	public void update(double ibmPrice, double aaplPrice, double googPrice);
	
}

STOCKGRABBER.JAVA

import java.util.ArrayList;

// Uses the Subject interface to update all Observers

public class StockGrabber implements Subject{
	
	private ArrayList<Observer> observers;
	private double ibmPrice;
	private double aaplPrice;
	private double googPrice;
	
	public StockGrabber(){
		
		// Creates an ArrayList to hold all observers
		
		observers = new ArrayList<Observer>();
	}
	
	public void register(Observer newObserver) {
		
		// Adds a new observer to the ArrayList
		
		observers.add(newObserver);
		
	}

	public void unregister(Observer deleteObserver) {
		
		// Get the index of the observer to delete
		
		int observerIndex = observers.indexOf(deleteObserver);
		
		// Print out message (Have to increment index to match)
		
		System.out.println("Observer " + (observerIndex+1) + " deleted");
		
		// Removes observer from the ArrayList
		
		observers.remove(observerIndex);
		
	}

	public void notifyObserver() {
		
		// Cycle through all observers and notifies them of
		// price changes
		
		for(Observer observer : observers){
			
			observer.update(ibmPrice, aaplPrice, googPrice);
			
		}
	}
	
	// Change prices for all stocks and notifies observers of changes
	
	public void setIBMPrice(double newIBMPrice){
		
		this.ibmPrice = newIBMPrice;
		
		notifyObserver();
		
	}
	
	public void setAAPLPrice(double newAAPLPrice){
		
		this.aaplPrice = newAAPLPrice;
		
		notifyObserver();
		
	}

	public void setGOOGPrice(double newGOOGPrice){
	
		this.googPrice = newGOOGPrice;
	
		notifyObserver();
	
	}
	
}

STOCKOBSERVER.JAVA

// Represents each Observer that is monitoring changes in the subject

public class StockObserver implements Observer {
	
	private double ibmPrice;
	private double aaplPrice;
	private double googPrice;
	
	// Static used as a counter
	
	private static int observerIDTracker = 0;
	
	// Used to track the observers
	
	private int observerID;
	
	// Will hold reference to the StockGrabber object
	
	private Subject stockGrabber;
	
	public StockObserver(Subject stockGrabber){
		
		// Store the reference to the stockGrabber object so
		// I can make calls to its methods
		
		this.stockGrabber = stockGrabber;
		
		// Assign an observer ID and increment the static counter
		
		this.observerID = ++observerIDTracker;
		
		// Message notifies user of new observer
		
		System.out.println("New Observer " + this.observerID);
		
		// Add the observer to the Subjects ArrayList
		
		stockGrabber.register(this);
		
	}
	
	// Called to update all observers
	
	public void update(double ibmPrice, double aaplPrice, double googPrice) {
		
		this.ibmPrice = ibmPrice;
		this.aaplPrice = aaplPrice;
		this.googPrice = googPrice;
		
		printThePrices();
		
	}
	
	public void printThePrices(){
		
		System.out.println(observerID + "\nIBM: " + ibmPrice + "\nAAPL: " + 
				aaplPrice + "\nGOOG: " + googPrice + "\n");
		
	}
	
}

GRABSTOCKS.JAVA

public class GrabStocks{
	
	public static void main(String[] args){
		
		// Create the Subject object
		// It will handle updating all observers 
		// as well as deleting and adding them
		
		StockGrabber stockGrabber = new StockGrabber();
		
		// Create an Observer that will be sent updates from Subject
		
		StockObserver observer1 = new StockObserver(stockGrabber);
		
		stockGrabber.setIBMPrice(197.00);
		stockGrabber.setAAPLPrice(677.60);
		stockGrabber.setGOOGPrice(676.40);
		
		StockObserver observer2 = new StockObserver(stockGrabber);
		
		stockGrabber.setIBMPrice(197.00);
		stockGrabber.setAAPLPrice(677.60);
		stockGrabber.setGOOGPrice(676.40);
		
		// Delete one of the observers
		
		// stockGrabber.unregister(observer2);
		
		stockGrabber.setIBMPrice(197.00);
		stockGrabber.setAAPLPrice(677.60);
		stockGrabber.setGOOGPrice(676.40);
		
		// Create 3 threads using the Runnable interface
		// GetTheStock implements Runnable, so it doesn't waste 
		// its one extendable class option
		
		Runnable getIBM = new GetTheStock(stockGrabber, 2, "IBM", 197.00);
		Runnable getAAPL = new GetTheStock(stockGrabber, 2, "AAPL", 677.60);
		Runnable getGOOG = new GetTheStock(stockGrabber, 2, "GOOG", 676.40);
		
		// Call for the code in run to execute 
		
		new Thread(getIBM).start();
		new Thread(getAAPL).start();
		new Thread(getGOOG).start();
		
		
	}
	
}

GETTHESTOCK.JAVA

import java.text.DecimalFormat;

public class GetTheStock implements Runnable{
	
	// Could be used to set how many seconds to wait
	// in Thread.sleep() below
	
	// private int startTime; 
	private String stock;
	private double price;
	
	// Will hold reference to the StockGrabber object
	
	private Subject stockGrabber;
	
	public GetTheStock(Subject stockGrabber, int newStartTime, String newStock, double newPrice){
		
		// Store the reference to the stockGrabber object so
		// I can make calls to its methods
				
		this.stockGrabber = stockGrabber;
		
		// startTime = newStartTime;  Not used to have variable sleep time
		stock = newStock;
		price = newPrice;
		
	}
	
	public void run(){
		
		for(int i = 1; i <= 20; i++){
		
			try{
				
				// Sleep for 2 seconds
				Thread.sleep(2000);
				
				// Use Thread.sleep(startTime * 1000); to 
				// make sleep time variable
			}
			catch(InterruptedException e)
			{}
			
			// Generates a random number between -.03 and .03
			
			double randNum = (Math.random() * (.06)) - .03;
			
			// Formats decimals to 2 places
			
			DecimalFormat df = new DecimalFormat("#.##");
			
			// Change the price and then convert it back into a double
			
	        price = Double.valueOf(df.format((price + randNum)));
			
			if(stock == "IBM") ((StockGrabber) stockGrabber).setIBMPrice(price);
			if(stock == "AAPL") ((StockGrabber) stockGrabber).setAAPLPrice(price);
			if(stock == "GOOG") ((StockGrabber) stockGrabber).setGOOGPrice(price);
			
			System.out.println(stock + ": " + df.format((price + randNum)) + 
					" " + df.format(randNum));
			
			System.out.println();
		
		}
	}
	
}

54 Responses to “Observer Design Pattern Tutorial”

  1. Saleh says:

    I can see my comments here only if I provide my name and email. Now this comment is only to enable me see my previous comment and responds if any. I use (Firefox & Google Chrome).

    • admin says:

      I have to approve all comments before they show up. I do this for security reasons. Sorry about any confusion. I promise you that I read every comment and reply to 95% of them

  2. Pralay Biswas says:

    Hi Derek,
    Am I getting this right? In the threaded version of the code, all that the runnable object does is to change the stock prices eh? As soon as a thread changes the stock price, the original notifyObserver() is called on the stockGrabber which then sends an update wave invoking the registered observer’s update right?
    P.S. Derek, I absolutely love your vidz, I am following the GoF and HFDP along with your vidz and they work fantastically well. Things that I don get in GoF – you make em so clear thru the tutes. God bless you for such wonderful work.
    Thanks,
    Pralay

    • admin says:

      Hi Pralay, Yes you are getting the idea. I don’t use just one book like most people seem to? I actually combined 8 sources for these tutorials. I’m glad you found them useful. Just understand that in 2 parts of this tutorial I actually deviate from the patterns used in the GOF book, for a different form that I found more useful from other sources. The Bridge and Interpreter patterns are the patterns I’m alluding to. Feel free to ask questions and I’ll do my best to help

  3. Pralay Biswas says:

    Also,
    I know I am asking way too much here. But do you think it would be possible to make some vids on big-data and stuff. I mean, say the first few lectures are more of ppts of Hadoop etc. And then slowly you get into mapreduce stuff. And show some examples, say the word count problem or terasort may be! It is so much in demand these dayz – any company that I interview with throws in a couple of questions on hadoop etc.
    Thanks yet again,
    Pralay

    • admin says:

      Interviewers are asking about Hadoop? Wow, I just started looking into it in the last few months because it has only been stable since last month! I’ll see what I can do. I’m planning on covering algoritms very soon

  4. lee says:

    Please, provide PPT, didn’t fully understand for a Chinese like me, poor english,

  5. Angel Valdes says:

    Best videos on this topic by far!!!
    Fast, Clear, and to the point!
    I am translating them to vb.net and Spanish and have been successful so far (observer and strategy) to use in my vb.net class as exercises for the students.

    Before your videos, I was not able to clearly understand any of the design patterns.
    Thanks a lot!!!

    Note: I only removed the threading part to keep it focus and simple. πŸ™‚

    • admin says:

      I’m very happy that you are enjoying them πŸ™‚ I worked to make everything understandable by pulling ideas from ever source and then simplifying. If you give me a bit more information on your other question I’ll do my best to help

  6. Angel Valdes says:

    What is the best way of changing the code so that the observers are only monitoring one of the three stock (each its own)?
    Thanks!

    • admin says:

      I’m going to be covering how to use the design patterns in my refactoring tutorial which will start very soon. I’d give you an answer now, but I’m not clear on what you are trying to do. I hope I provide your answer in that tutorial

  7. Anonymous says:

    Best explanation of design pattern ever !!

  8. Rajkumar says:

    Very good explanation.Thanks.

  9. Sourabh Sharma says:

    Ah Derek ! The More I go through your tutorials the more a voice echoes in my head “This guy’s a genius πŸ˜€ ” Amazing πŸ˜€

  10. Alex says:

    This tutorial is very helpful! But I am having problems understanding it as I do not know java. Do you have a copy of this code for C++ instead of java? Or do you have a link to another observer tutorial for c++? I have been looking around for one but none of them are as good as your tutorial.

  11. pcual says:

    Hello,
    May I ask why in the uml diagram IBMPrice and AAPPrice look like class that extend Observer.

  12. Kunal says:

    Hi,

    As you mentioned there is loose coupling between observer and subject but from code it seems that they are tied with each other..can you please clarify. Apology in advance for my absurd question.

    Thanks
    Kunal

    • Derek Banas says:

      That isn’t an absurd question. When trying to avoid coupling there are always trade offs. The goal is to eliminate dependence as much as possible, but you still need to provide a way for objects to interact. With experience you’ll learn to find the sweet spot that you are most comfortable with.

  13. shouket says:

    Thank you very much for such a nice series of lectures. I have almost gone through all of your lectures on design patterns. They are wonderful and knowledge increasing.
    One thing that I can not understand is that in the uml the IBM and AAPLprice are shown as classes whereas in the code I don’t see anything like a class by these names.
    Will you please make it clear what is it in reality.
    Appologies in advance for this question if it does make a sense.

    • Derek Banas says:

      You’re very welcome πŸ™‚ Those stocks basically are just the data being passed around. They could actually represent pretty much any type of data in this pattern. I hope that helps. Sorry I couldn’t get to you quicker

  14. Shpend says:

    Hi!

    Im quite new at programming and theres something i cant understand. Why arent “events” used in the observer pattern(java) like it is in c#. Basically im trying to figure out the main differences between observer pattern in java vs c#.

  15. Al says:

    Hi Derek, I have observer pattern working which updates the GUI. I am in a situation where my model completes an operation and it wants to ask user if they want to save the results? It notifies GUI to bring up this dialog but I think GUI sending feedback from this notification would be against the norms and will cause problems (it will send all observers to display the dialog for a start which is bad!). Should the ‘SaveResults’ thing be launched from GUI after operation is complete? This operation (Say Operation1)can be performed from several dialogs and I would like it to have the same behavior of asking user if they want to save results. Can I package that as re-usable code somehow? Thanks.

  16. DunderKlumpen says:

    Hey there,

    I’m getting the following error:
    ” Exception in thread “Thread-1” Exception in thread “Thread-0” Exception in thread “Thread-2” java.lang.NumberFormatException: For input string: “677,59” “.

    I’m guessing this has to do with me living in Sweden where we use commas to separate the decimals instead of dots?

    If that is indeed the case, how could I make it work?

    Thanks!

  17. Ramesh says:

    Hello Sir,

    I took exact code but till 18th line of GrabStock.java to check simple (without threading) functionality.
    But I am receiving following error,

    New Observer: 1
    Exception in thread “main” java.lang.NullPointerException
    at controller.StockGrabber.register(StockGrabber.java:14)
    at controller.StockObserver.(StockObserver.java:29)
    at controller.GrabStocks.main(GrabStocks.java:14)

    Please suggest!
    Thanks.

  18. Baibhav says:

    i followed along your tutorial but ,typed the codes along with you, but I cannot pass the stockGrabber as an argument when constructing StockObserver object(ie observer1)

    StockGrabber stockGrabber = new StockGrabber(); StockObserver observer1 = new StockObserver(stockGrabber);//ERR

    because: StockObserver in class StockObserver cannot be applied to given types:
    Required: Subject
    Found: StockGrabber

  19. Ramtin says:

    Derek, you’re the man! You really saved my life with your tutorials! πŸ™‚

    Keep it up. You are a brilliant teacher.

    Best regards from Germany.

  20. weldu Hashenge says:

    U’re Amazing bro.. All so simple when u explain it ^^thanks much^^ Happy to watch your series! ο»Ώ

  21. Praveena says:

    Good Explanation ! Worth Watching. Thanks a ton. U can include examples of Design Patterns used in JDK since its based on Java in each pattern.
    Eg: All implementations of java.util.EventListener (practically all over Swing thus)

  22. Ria says:

    Hi Derek!! Great videos and explanation!!! Thanks very much πŸ™‚

    I have been trying to apply patterns on a simple project that I am working on. I have this make make payment page on my app and I need the different fields like Card holder name, card number, expiry date and cvv to listen to keypad which is the subject. I am not sure if observer pattern is the best I can use here.

    I need only the name field to be updated wen I enter a name on the keypad object but I am making all by observers get notified about it through this observer pattern. Is it the right way to implement. Please help me and correct me if I am wrong.

    Thank you.

  23. Rekha says:

    Love this

  24. Anonymous says:

    U are really amazing… Ur explained is too good and simple. All these days I was thinking design patterns as Mount Everest. U made it simple. Thanks a lot.

  25. k aravind says:

    dude ur awesome…:)
    thanks alot..:)
    at first when i tried reading from google i never understood a thing..:(
    thanks alot for videos.Concepts explained are crystal clear..:)
    If possible can you provide some programs to work on simple programs, it would be really helpful..:)
    Thanks again..:)

    • Derek Banas says:

      Thank you πŸ™‚ I do my best. I’m planning to make a ton of free Android apps that will allow everyone to practice everything I have on my site. I’m working on them

  26. Bharat says:

    Hi Derek,

    Thanks a lot for amazing set of tutorials.

  27. Wiert says:

    You’ve really helped me pass my exams with these tutorials!
    Thanks a lot!

Trackbacks/Pingbacks

  1. Design Patterns Cheat Sheet by Richard Sumilang - […] Observer Design Pattern: Contains an object usually referred to as the subject that maintains a a list of dependent…

Leave a Reply

Your email address will not be published.

Google+