我的 C1 类具有所有静态成员(变量和方法)。它还有一个 C2 类型的对象数组 A1,这些对象是可观察的。我希望 C1 成为记录 C2 变化的观察者,然后使用 A1 中包含的引用将这些变化应用于对象。我正在使用 C1 的实例,以便可以将其添加为 C2 对象的观察者。
观察者可观察的设计模式是否适合这种情况?如果是,那么我是否正确应用它?
import java.util.*;
class FlightStatusChangeEvent{
int status;
Flight flight;
FlightStatusChangeEvent(int statusCode, Flight flight){
this.status = statusCode;
this.flight = flight;
}
public int getStatus(){return this.status;}
public Flight getFlight(){return this.flight;}
}
class Flight extends Observable{
int status;// 0 = on time, -1 = late, +1 = before scheduled time
public void updateStatus(int statusCode){
this.status = statusCode;
FlightStatusChangeEvent fsce = new FlightStatusChangeEvent(status, this);
setChanged();
notifyObservers(fsce);
}
}
class FlightStatusMonitor implements Observer{
public static ArrayList<Flight> flights = new ArrayList<Flight>();
//keep calling this method every 10 sec to get latest flight status
public void displayStatusOfFlights(){
//print all flight statuses in array list - flights
}
public void update(Observable flight, Object flightStatusEvent){
FlightStatusChangeEvent fsce = (FlightStatusChangeEvent) flightStatusEvent;
Flight fl = fsce.getFlight();
int status = fsce.getStatus();
//find the flight in array flights and then update its status
}
}