If we mix the construction of a complex assembly with the construction of its components, then we need to rewrite the assembly constructor in order to use a different collection of components.
Decouple the construction of the assembly from the construction of the components. This can be done by passing the assembly constructor an abstract factory responsible for creating the components:
Here's a template:
A
process consists of a state (of type double) and four types of tasks:
interface StartTask {
double initState(); // compute init state
}
interface LoopTask {
double nextState(double state); // compute next state from current
state
}
interface TestTask {
boolean isGoal(double state); // = true if current state == goal
state
}
interface EndTask {
void displayState(double state); // display the final state
}
The
execute method initializes the process's state. The loop task repeatedly
updates the state until the goal is reached. The end task displays the state:
public class Process {
private double state;
private StartTask task1;
private LoopTask task2;
private TestTask task3;
private EndTask task4;
public void execute() {
state = task1.initState();
while (!task3.isGoal(state)) {
state =
task2.nextState(state);
}
task4.displayState(state);
}
// etc.
}
For
example, the following tasks approximate the square root of n:
class RootInit implements StartTask {
public double initState() {
return 1.0;
}
}
class RootLoop implements LoopTask {
private double n;
public RootLoop(double k) { n = k; }
public double nextState(double state) {
return state - (state * state - n)/(2 * state);
//
}
}
class RootTest implements TestTask {
private double n;
private double delta = 1e-4; // error tolerance
public RootTest(double k) { n = k; }
public boolean isGoal(double state) {
return Math.abs(state * state - n) <= delta;
}
}
class RootEnd implements EndTask {
public void displayState(double state) {
System.out.println("root = " + state);
}
}
Here's a solution: