Design Patterns: Observer Pattern
Tags: patterns, java, design
Published: 2017-10-01 19:41:53

---
title: "Design Patterns: Observer Pattern"
published: true
tags: patterns, java, design, 
canonical_url: https://henricodesjava.blog/2017/10/01/design-patterns-observer-pattern/
---

_originally posted on my blog at [henricodesjava.blog](https://henricodesjava.blog/)_

Hi everyone! Chapter two in&nbsp;[Head First Design Patterns: A Brain-Friendly Guide](https://www.amazon.com/Head-First-Design-Patterns-Brain-Friendly/dp/0596007124/ref=sr_1_1?ie=UTF8&qid=1505068308&sr=8-1&keywords=head+first+design+patterns)&nbsp;is all about the Observer Pattern. They make note of how fundamental and frequently this pattern is used. And also allude to the idea that future patterns in this book are based on this and other pattern combinations. So lets talk about the Observer Pattern.

The problem this pattern is trying to solve is about communication and management. A simple abstract example given in the text is about a newspaper publishing company, and its subscribers. Technically this relationship can be categorized as a ONE-TO-MANY relationship, one publisher, and many subscribers. The text uses the term â€˜ **Subject** â€˜ to refer to the publisher, and the term â€˜ **Observer** â€˜ to refer to the subscribers.

Next I’ll give a more concrete example. I’ll use an example slightly different from the text to help illustrate the idea. Lets say we are a finance startup, and we have an idea for a smartwatch app that can communicate with all your financial institutions to give you a bird’s eye view of your finances. For example it can show you balances of your checking account, or show you prices of stocks you own. What we have access to is a class that can return these values for us, lets call this class **FinancialData**. For the purposes of this example, we don’t care how it retrieves this information.

![Screen Shot 2017-09-30 at 12.28.17 AM.png](https://henricodesjava.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-12-28-17-am.png?w=232&h=166)

Below is a naive implementation of our smart watch app, along with an explanation. Of course all of this is just pseudo code, no actual smartwatch code.

![Screen Shot 2017-09-30 at 1.24.50 AM.png](https://henricodesjava.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-1-24-50-am1.png?w=656)

There are a few things wrong with this implementation. First we are in violation of a design principle from back in chapter one.&nbsp;_Identify the aspect of your application that vary and separate them from what stays the same.&nbsp;_The lines with the green arrows represent a different screen on the watch, and in the future we might want to add more screens. When that times comes, changes to this class are unfortunately unavoidable. The lines with red arrows are retrieving financial data, and while this too can change, it would be a change caused by a API change and not a change on our client side code. We are also in violation of another design principle:&nbsp;_Program to an interface, not an implementation.&nbsp;_If only there was a way we can neatly separate code that changes, from code that doesn’t, and also not program to an implementation? Introducing, the Observer pattern!

**The Observer Pattern** : Defines a one-to-many dependency between objects so that when one object changes state, all of it’s dependents are notified and updated automatically.

We will accomplish this, and introduce loose coupling by the use of interfaces. Lets illustrate this definition with a class diagram.

![Screen Shot 2017-09-30 at 10.56.06 AM](https://henricodesjava.files.wordpress.com/2017/09/screen-shot-2017-09-30-at-10-56-06-am.png?w=520&h=536)

&nbsp;

Now with these class diagrams as a guide, lets take a look at an implementation for our smart watch app. First the two interfaces are below.

```java
public interface Subject {
	public void registerObserver(Observer o);
	public void removeObserver(Observer o);
	public void notifyObservers();
}

public interface Observer {
	public void upate(Object obj);
}
```

&nbsp;  
Next lets take a look at our new FinancialData class that implements the Subject interface.

```java
public class FinancialData implements Subject {
   private ArrayList observers;

   private float checkingBalance;
   private float savingsBalance;

   private float stockValue;
   private float fourOnekValue;

   private float weekSpending;
   private float monthSpending;

   public FinancialData(){
      observers = new ArrayList();
   }

   public void registerObserver(Observer o){
      observers.add(o);
   }

   public void removeObserver(o){
      int i = observers.indexOf(o);
      if(i > 0){
         observers.remove(i);
      }
   }

   public void notifyObservers(){
      for(int i = 0; i<observers.size(); i++){
         Observer observer = (Observer)observers.get(i);
         observer.update(this);
      }
   }
   
   public void measurementsChanged(){
      notifyObservers();
   }

   public void setNewBalanceData(float val1, float val2){
      this.checkingBalance = val1;
      this.savingsBalance = val2;
      measurementsChanged();
   }
   
   public void setNewInvestmentData(float val1, float val2){
      this.stockValue = val1;
      this.fourOnekValue = val2;
      measurementsChanged();
   }
   
   public void setNewSpendingData(float val1, float val2){
      this.weekSpending = val1;
      this.monthSpending = val2;
      measurementsChanged();
   }
   // other FinancialData methods here
   // including getter methods for balance, investment, and spending values
}
```

&nbsp;  
Now lets take a look at one of our observers, the Balance smart watch screen.

```java
public class BalanceScreen implements Observer {
   private float checkingBal;
   private float savingsBal;
   private Subject financialData;

   public BalanceScreen(Subject financialData){
      this.financialData = financialData;
      financialData.registerObserver(this);
   }

   public void update(Object obj){
      if( obj instanceof FinancialData){
         FinancialData fd = (FinancialData) obj;
         this.checkingBal = fd.getCheckingBalance();
         this.savingsBal = fd.getSavingsBalance();
      }
      display();
   }
   // other BalanceScreen methods here
}
```

Finally lets take a look at a program to glue all this together.

```java
public class SmartWatch {
	public static void main(String[] args){
		FinancialData financialData = new FinancialData();

		BalanceScreen balanceScreen = new BalanceScreen(financialData);
		InvestmentScreen investmentScreen = new InvestmentScreen(financialData);
		SpendingScreen spendingScreen = new SpendingScreen(financialData);

		// not using an actualy finance api, so we set values manually
		financialData.setNewBalanceData(348.12, 3600.87);
		financialData.setNewInvestmentData(899.12, 45000.65);
		financialData.setNewSpendingData(210.34, 677.45);

		// at this point we should see print statements for all 3 screens
	}
}
```

There you have it! We implemented the interfaces and created some code to test it. Now please note I haven’t actually got this code running, so there might be a bug or two in these lines. For a future post I’ll have to create a project and push this working code up on github. Thanks for reading !ðŸ‘‹ðŸ½


(originally posted at my personal blog: https://henricodesjava.blog)
  
[![](http://feeds.wordpress.com/1.0/comments/henricodesjava.wordpress.com/186/)](http://feeds.wordpress.com/1.0/gocomments/henricodesjava.wordpress.com/186/) ![](https://pixel.wp.com/b.gif?host=henricodesjava.blog&blog=133476896&post=186&subd=henricodesjava&ref=&feed=1)