Design Patterns Java™ Workbook

(Michael S) #1
Appendix B. Solutions

SOLUTION 26.2....................................................................................................................................


The call to notify() in the pop() method will wake up a thread that was waiting for
the stack to make some room. The awakened thread must then wait to obtain the monitor.
Because the pop() method is synchronized, it holds the monitor until the method
completes.


SOLUTION 26.3....................................................................................................................................


The problems in the model are as follows.



  • The Rocket class can't extend two classes.

  • The Rocket.clone() method can't have the same signature as and a different
    return type from the method it overrides.

  • The Rocket.clone() method can't reduce visibility from protected to
    private.

  • The Rocket.clone() method can't throw an extra exception. You could cure this
    problem if you made RocketCloneException an extension of
    CloneNotSupportedException.


SOLUTION 26.4....................................................................................................................................


Questionable aspects of the model follow.



  • The FireworkCollection class is useful as a collection that contains only
    a certain type of object. However, such a collection is either a list or a set, and it
    should be named accordingly.

  • The FireworkCollection class stores Firework objects in a set instead of a list.
    This makes it difficult to imagine what a call to, say, get(0) will return.

  • The FireworkCollection class has an iterator() function, which is good, but
    it returns Iterator, which is questionable. The returned iterator will have a next()
    method that returns an Object that the caller will have to cast to Firework. This
    defeats the idea of having a separate collection class for fireworks.

  • The fireworks hierarchy comprehends the fact that a firework's type does not always
    indicate whether the firework will explode.


For example, rockets may or may not explode, although firecrackers always explode
and sparklers never do. The setExplodes() method allows flexibility in modeling
firework types but also allows setting a Sparkler object to be an exploding type of
firework. You should avoid this type of modeling error. In this case, it might work to
create an ExplodingFirework subclass of Firework.


  • The setExplodes() method of Firecracker throws
    an IllegalArgumentException if the argument is false, as all firecrackers
    explode. It is inconsistent to have this method throw an exception without extending
    this thought to Sparkler, whose instances should never explode.

Free download pdf