Java Reference
In-Depth Information
At this point we can also better define the responsibility of the class
Format
and its derived classes. It must provide two main functionalities:
■
parsing: convert a string representation of a number to the internal repre-
sentation, i.e. to a
Rational
object; this is performed by method
parse()
;
■
printing: convert a number from the internal representation to a string
format; this is done by method
toString()
.
Class
Format
is abstract therefore it only defines these methods and dele-
gates their implementation to its derived classes. A relevant feature of the
format classes is to provide the name of the format. This makes it possible to
know which the current format is.
To better understand how the polymorphic implementation of the format
works, we can observe a simple scenario that involves the parsing of an
operand provided by the command line interpreter. The collaboration
diagram of Figure 6.6 describes this scenario.
The sequence of operations is as follows. The command interpreter inserts
a new operand in the calculator by means of the
addOperand
method (1).
This method delegates the task of parsing the string to the current format
(i.e. to the object currently connected through the format relationship). In
this case it is an instance of the
FixedPoint
class; this is done invoking the
method
parse()
(2). The method
parse
creates a new
Rational
object, which
will contain the value, and returns it. Before terminating, the
addOperand()
method links the value returned by
parse()
as the second operand of the
calculator, i.e. it is linked to the operand in the role
operand_1
.
6.4.3
Implementation
In order to have well-structured code, all the calculator-related classes are
put into the multi-format package. Therefore all the classes are preceded by
the package declaration:
package
multiformat;
Class
Rational
implements the internal representation of operands and
results. It represents rational numbers by means of a numerator and a
denominator.
1 : addOperand()
2 : parse()
command :
Command
format :
FixedPoint
calc
calc :
Calculator
format
3 : new
rational :
Rational
Figure 6.6
Collaboration of calculator classes