I have a class that monitors the stock market. It holds 2 values (doubles) the daily high and the daily low. I want to monitor these variables from another class and take action if either changes. (i.e. change a limit order)
So, I have a class LiveOrderBook extends Observable and two methods inside that update the price:
public void setDailyLow(double price){
low = price;
setChanged();
notifyObservers(low);
}
public void setDailyHigh(double price){
high = price;
setChanged();
notifyObservers(high);
}
I need to observe these price variables so I made a class PriceObserver implements Observer. My plan is to create PriceObserver objects inside my Bid class that changes stock market bids.
My PriceObserver class
private double low;
private double high;
public PriceObserver(){
low = 0;
high = 0;
}
public void update(Observable arg0, Object arg1) {
// TODO Auto-generated method stub
}
How do I now specify which double should be updated? I can't check if arg0 == the variable name from the other class, so how is this done?
An easy (and useful) approach is to first create different event classes that can get dispatched:
public class LowPriceChangedEvent {
private double price;
// Constructor and getter up to you.
}
public class HighPriceChangedEvent {
private double price;
// Constructor and getter up to you.
}
Now you can dispatch these events in your LiveOrderBook class:
public void setDailyLow(double price){
low = price;
setChanged();
notifyObservers(new LowPriceChangedEvent(low));
}
public void setDailyHigh(double price){
high = price;
setChanged();
notifyObservers(new HighPriceChangedEvent(low));
}
Your PriceObserver now easily can distinguish the events by doing a simple instanceOf check:
public class PriceObserver implements Observer {
@Override
public void update(Observable o, Object arg) {
if (arg instanceOf LowPriceChangedEvent) {
...
} else if (arg instanceOf HighPriceChangedEvent) {
...
} else {
...
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With