Java Reference
In-Depth Information
Calculator
<<
abstract
>>
Format
Command
FractionalFormat
FixedPointFormat
FloatingPointFormat
create
Figure 6.4
The classes that handle number format conversions
Sidebar 6.1 Dynamic behaviour
The problem of changing the behaviour of a program (or some of its parts) at run
time is very common.
Let's focus on a simplified version of this problem. We consider a class
(
Changing
) that has an entry method (
public void perform()
) whose behaviour can
vary during the execution of the program, and method
public void setBehavior()
used to switch from one behaviour to the other. There are two possible solutions:
to implement all the possible behaviours inside method
perform()
using a big
switch construct that selects the code to be executed;
■
to encapsulate every specific behaviour in a different object to be passed to
class
Changing
.
■
The first solution requires a status attribute that keeps track of the current
behaviour. The entry method contains a switch (or chain of else
-
if) to select the
appropriate behaviour.
This solution is quite simple: class
Changing
contains the entry method and the
behaviour selection method.
public class
Changing {
int
behavior
#
0;
public static final int
FIRST_BEHAVIOR
#
1;
public static final int
SECOND_BEHAVIOR
#
2;
public void
setBehavior(
int
newBehavior){ behavior
#
newBehavior; }
public void
perform(){
switch
(behavior){
case
1: /* B1 */
case
2: /* B2 */
}
}
}
The following code fragment shows the use of this solution:
Changing chObject
#
new
Changing(;
chObject.setBehavior(Changing.FIRST_BEHAVIOR);
chObject.perform();