BruceEckel / OnJava8-Examples

Code Examples for the book "On Java 8"

Home Page:http://www.OnJava8.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

The example of ObservedFlower flung me into confusion

merorin opened this issue · comments

commented

I'm learning about Design Pattern recently and the example of ObservedFlower in Chapter Callback confuses me.

As the comment in source code said:

public class ObservedFlower {

    public static void main(String[] args) {
        Flower f = new Flower();
        Bee
                ba = new Bee("A"),
                bb = new Bee("B");
        Hummingbird
                ha = new Hummingbird("A"),
                hb = new Hummingbird("B");
        f.opening.addObserver(ha.openObserver());
        f.opening.addObserver(hb.openObserver());
        f.opening.addObserver(ba.openObserver());
        f.opening.addObserver(bb.openObserver());
        f.closing.addObserver(ha.closeObserver());
        f.closing.addObserver(hb.closeObserver());
        f.closing.addObserver(ba.closeObserver());
        f.closing.addObserver(bb.closeObserver());
        // Hummingbird B decides to sleep in:
        f.opening.deleteObserver(hb.openObserver());
        // A change that interests observers:
        f.open();
        f.open(); // It's already open, no change.
        // Bee A doesn't want to go to bed:
        f.closing.deleteObserver(ba.closeObserver());
        f.close();
        f.close(); // It's already closed; no change
        f.opening.deleteObservers();
        f.open();
        f.close();
    }
}
/* Output:
Bee B's breakfast time!
Bee A's breakfast time!
Hummingbird B's breakfast time!
Hummingbird A's breakfast time!
Bee B's bed time!
Bee A's bed time!
Hummingbird B's bed time!
Hummingbird A's bed time!
Bee B's bed time!
Bee A's bed time!
Hummingbird B's bed time!
Hummingbird A's bed time!
*/

"Hummingbird B decides to sleep in", so we delete the open observer of hb.

However, we still see ,"Hummingbird B's breakfast time!" in the result printed.

Hb decided to sleep in, didn't it? How could HB still have breakfast?

I've debugged the code and found that the Vector, obs, failed to remove element.

public synchronized boolean removeElement(Object obj) {
        modCount++;
        int i = indexOf(obj);
        if (i >= 0) {
            removeElementAt(i);
            return true;
        }
        return false;
    }

The indexOf(obj) returns -1.

So as "Bee A doesn't want to go to bed".

I tried to compare the code with Thinking in Java 4th but only to found that there is no Patterns chapter on it.

Is there something I've missed?

Or it is a bug just because hashCode&equals are not override due to lambda expression?

Yes, this was a problem. It will be fixed in the upcoming (February 2021) release.