You can use polymorphism. For example, let's say you have an abstract class that extends Observable :
import java.util.Observable; public abstract class DashboardDataSource extends Observable { public abstract int getLevel(); }
Then you have two classes that inherit from DashboardDataSource (in fact, you have as many as you need, I just use two as an example):
public class FuelLevel extends DashboardDataSource { public void saySomething(){ setChanged(); notifyObservers(); } @Override public int getLevel() {
AND
public class BatteryLevel extends DashboardDataSource { public void saySomething(){ setChanged(); notifyObservers(); } @Override public int getLevel() {
Then you can have a Dashboard like this:
public class Dashboard implements Observer { @Override public void update(Observable o, Object arg) { DashboardDataSource d = (DashboardDataSource) o; System.out.println (d.getLevel()); } }
In this case, you simply throw the Observable o on the DashboardDataSource and call the implementation of its abstract method, which will be specific to anyone that DashboardDataSource makes a notification for your Dashboard (in this example, a FuelLevel or BatteryLevel )
source share