Java Reference
In-Depth Information
Examples
To implement different representation formats for
numbers an abstract interface can be declared. It defines
two methods that can be used to convert between
String
and
double
:
interface
Format {
String toString(
double
number);
double
parse(String number);
}
Then we can define as many concrete behaviours as there
are formats. For instance the concrete behaviour for the
floating point format can be implemented as:
class
FloatingPointFormat
implements
Format {
String toString(
double
number){
// convert to a floating point
// formatted string
}
double
toDouble(String number) {
// parse a floating point formatted
// string
}
}
The client that wants to perform a conversion uses the
abstract interface:
void
printNumber(
double
number, Format
format){
System.out.println
(format.toString(number));
}
The format actually adopted depends on the effective class
of the object passed as argument format.
Force resolution
The clients always access the behaviour through the same
invariable interface.
The behaviour varies according to the effective class of the
format object.
The inheritance hierarchy makes the different behaviours
explicit.
Design rationale
This pattern leverages the polymorphism and dynamic
binding. The
Context
can be linked to any class that
implements the
Strategy
interface; when it invokes one of
the operations, the one defined in the actual class of the
object is activated.