Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
An Observer design pattern implementation example based on Ruby's Observable API
import java.util.Random;
public class Price {
private int value;
public Price(int value) {
this.value = value;
}
public int getValue() {
return value;
}
public boolean equals(Price otherPrice) {
if(otherPrice != null) {
return this.getValue() == otherPrice.getValue();
} else {
return false;
}
}
public static Price fetch() {
return new Price(new Random().nextInt(300));
}
}
import java.util.Observable;
public class Ticker extends Observable implements Runnable {
public void run() {
Price lastPrice = null;
while(true) {
Price price = Price.fetch();
System.out.format("\nCurrent price: %d", price.getValue());
if(!price.equals(lastPrice)) {
this.setChanged();
lastPrice = price;
notifyObservers(lastPrice);
try {
Thread.sleep(1000);
} catch( InterruptedException e ) {
break;
}
}
}
}
}
public class TickerRunner {
public static void main(String[] args) throws InterruptedException {
Ticker ticker = new Ticker();
new WarnLow(ticker, 80);
new WarnHigh(ticker, 120);
ticker.run();
}
}
import java.util.Observer;
public abstract class Warner implements Observer {
protected int limit;
protected Price price;
protected Ticker ticker;
Warner(Ticker ticker, int limit) {
this.ticker = ticker;
this.limit = limit;
ticker.addObserver(this);
}
}
import java.util.Observer;
import java.util.Observable;
public class WarnHigh extends Warner {
public WarnHigh(Ticker ticker, int limit) {
super(ticker, limit);
}
public void update(Observable observable, Object obj) {
if (obj instanceof Price) {
price = (Price) obj;
if(price.getValue() > this.limit) {
System.out.format("\n+++ Price above %d: %d", limit, price.getValue() );
}
}
}
}
import java.util.Observer;
import java.util.Observable;
public class WarnLow extends Warner {
public WarnLow(Ticker ticker, int limit) {
super(ticker, limit);
}
public void update(Observable observable, Object obj) {
if (obj instanceof Price) {
price = (Price) obj;
if(price.getValue() < this.limit) {
System.out.format("\n--- Price bellow %d: %d", limit, price.getValue() );
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.