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. |