Solutions to other chapters:
  1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26  
Java Methods Home Page Skylight Publishing



Java Methods A & AB:
Object-Oriented Programming and Data Structures

Answers and Solutions to Exercises

Chapter 26

1.   See JM\Ch26\Exercises\Solutions\EasyDate.java.
2.   See the complete solution in the Ch26\Exercises\Solutions\Question2 folder.
9.  

If we make a composite experssion (SumExpression and ProductExpression) Observable, how will it know when its left or right components have changed? In general in MVC, the model must be self-contained. If some of its fields change independently, outside the model, the MVC design breaks down.

One possible solution to this problem is to make a composite object both Observable and Observer and attach it as an Observer to all its components. When one of its components changes, the composite will be notified and then it can update its view and/or pass the change along to other composites that hold this one as a component.

In our example, the following steps will make it work:

  • Turn Expression from an interface into an abstract class that extends Observable.

  • Make Variable extend Expression and add code to notify observers when its value is set.

  • Define another abstract class, CompositeExpression derived from Expression, and make it implement Observer. Add a constructor that attaches this object to left and right as an observer and add an update method that notifies other observers of a change. Also add getLeft and getRight methods.

  • Derive SumExpression and ProductExpression from CompositeExpression, providing appropriate getValue and toString methods.

Copyright © 2006 by Skylight Publishing