Java observer pattern example

Observer pattern is used to observe the change of an object and update all related objects that is related to this changed object. In this example, gold is the object to observe, when the gold amount changes, the currency value also changes.

Gold.java

import java.util.ArrayList;
import java.util.List;

public class Gold {
	
   private List<Observer> observers = new ArrayList<Observer>();
   private double ounce;

   public double getOunce() {
      return ounce;
   }

   public void setOunce(double amount) {
      this.ounce = amount;
      notifyAllObservers();
   }

   public void attach(Observer observer) {
      observers.add(observer);		
   }

   public void notifyAllObservers(){
      for (Observer observer : observers) {
         observer.update();
      }
   } 	
}

Observer.java

public abstract class Observer {
   protected Gold gold;
   public abstract void update();
}

CnyObserver.java

public class CnyObserver extends Observer {

	private double rate = 8000;
    public CnyObserver(Gold gold) {
       this.gold = gold;
       this.gold.attach(this);  
    }

    @Override
    public void update() {
    	System.out.println( "CNY amount: " + gold.getOunce() * rate );
    }
}

DollarObserver.java

public class DollarObserver extends Observer{
	
	private double rate = 1220;
    public DollarObserver(Gold gold) {
    	this.gold = gold;
    	this.gold.attach(this);
   }

    @Override
    public void update() {
    	System.out.println( "Dollar Amount: " + gold.getOunce() * rate ); 
    }
}

EuroObserver.java

public class EuroObserver extends Observer{
	private double rate = 1000;
	public EuroObserver(Gold gold) {
		this.gold = gold;
		this.gold.attach(this);
	}

	@Override
	public void update() {
		System.out.println( "Euro amount: " + gold.getOunce() * rate ); 
	}
}

ObserverPattern.java

public class ObserverPattern {
	
   public static void main(String[] args) {
      Gold gold = new Gold();
      new EuroObserver(gold);
      new CnyObserver(gold);
      new DollarObserver(gold);

      System.out.println("10 ounces of gold:");	
      gold.setOunce(10);
      
      System.out.println("\n\ngold increased from 10 to 20 ounces:");	
      gold.setOunce(20);
   }
}

output:

10 ounces of gold:
Euro amount: 10000.0
CNY amount: 80000.0
Dollar Amount: 12200.0


gold increased from 10 to 20 ounces:
Euro amount: 20000.0
CNY amount: 160000.0
Dollar Amount: 24400.0

Search within Codexpedia

Custom Search

Search the entire web

Custom Search