你可以使用多态性。例如,假设您有一个扩展的抽象类Observable
:
import java.util.Observable;
public abstract class DashboardDataSource extends Observable {
public abstract int getLevel();
}
Then you have two classes that inherit from DashboardDataSource
(actually you have as many as you need, I'm just using two as an example):
public class FuelLevel extends DashboardDataSource {
public void saySomething(){
setChanged();
notifyObservers();
}
@Override
public int getLevel() {
// TODO Auto-generated method stub
return 50;
}
}
And
public class BatteryLevel extends DashboardDataSource {
public void saySomething(){
setChanged();
notifyObservers();
}
@Override
public int getLevel() {
// TODO Auto-generated method stub
return 20;
}
}
You could then have a Dashboard
like so:
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 just cast the Observable o
to a DashboardDataSource
and call the implementation of its abstract method, which will be specific to whatever DashboardDataSource is making the notification to your Dashboard
(in this example a FuelLevel
or BatteryLevel
)