0

我的 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

}


}
4

1 回答 1

0

这就是在您的案例中如何实现观察者模式:

class FlightStatusEvent {

    int status;
    Flight flight;

    FlightStatusEvent(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;
        FlightStatusEvent fsce = new FlightStatusEvent(status, this);
        setChanged();
        notifyObservers(fsce);

    }

}

class FlightStatusMonitor implements Observer {

    public ArrayList<Flight> flights = new ArrayList<Flight>();

    public void displayStatusOfFlights() {
        for(Flight f : flights) {
            System.out.println("Flight " + f + ", status = " + f.status);
        }
    }

    public void update(Observable flight, Object flightStatusEvent) {
        displayStatusOfFlights();
    }

    public static void main(String[] args) {
        FlightStatusMonitor fsm = new FlightStatusMonitor();

        Flight f1 = new Flight();
        f1.addObserver(fsm);
        Flight f2 = new Flight();
        f2.addObserver(fsm);

        ArrayList<Flight> flights = new ArrayList<Flight>();
        flights.add(f1);
        flights.add(f2);

        fsm.flights = flights;
        fsm.displayStatusOfFlights();

        // this will trigger observer pattern event.
        f1.updateStatus(1);
    }

}
于 2013-03-24T07:43:50.653 回答