bethrobson / Head-First-Design-Patterns

Code for Head First Design Patterns book (2020)
3.15k stars 1.92k forks source link

The BPM display bugs of BeatModel.java and HeartModel.java in MVC compound pattern #35

Open newryu opened 2 years ago

newryu commented 2 years ago

BPM display bugs in BeatModel.java

Input bpm 100, click Set, then click Start. The view will display 100, but actually the bpm is 90. And some other cases of bpm display bugs ...

Original Code

public class BeatModel implements BeatModelInterface, Runnable {
    public void on() {
        bpm = 90;
        //notifyBPMObservers();
        thread = new Thread(this);
        stop = false;
        thread.start();
    }

    public void off() {
        stopBeat();
        stop = true;
    }

    // ...
}

New Code

public class BeatModel implements BeatModelInterface, Runnable {
    public void on() {
        bpm = 90;
        notifyBPMObservers();
        thread = new Thread(this);
        stop = false;
        thread.start();
    }

    public void off() {
        stopBeat();
        stop = true;
        bpm = 0;
        notifyBPMObservers();
    }

    // ...
}

BPM display bugs in HeartModel.java

Since bpmOutputLabel is null in DJView.java on startup, the bpmOutputLabel will display "offline" for a short time if the heart rate doesn't change on startup.

For example, the heart rate is 60 on startup, lastrate is -1, rate != lastrate, then lastrate = rate = 60, and notifies the view to update bpmOutputLabel. But the bpmOutputLabel is null, no update. If the rate is 60 and doesn't change for a short time, since lastrate has already changed to 60, the bpmOutputLabel will not be updated for a short time too.

Original Code

if (rate < 120 && rate > 50) {
    time += change;
    notifyBeatObservers();
    if (rate != lastrate) {
        lastrate = rate;
        notifyBPMObservers();
    }
}

// ...

New Code

if (rate < 120 && rate > 50) {
    time += change;
    notifyBeatObservers();
    notifyBPMObservers();
}

// ...

And delete int lastrate = -1; in Line 19