Problem: How to decide at runtime which program to execute (e.g. user types in string name)?
Solution: Dynamic Starter Pattern
Outline: The String name of a class, with a start() method, is converted to a Class, converted to an Object, and then the start() method is called.
UML is shown for #1 (which means ConcreteProgram1), but should be able to work for any number of ConcretePrograms
Main() call is just used for testing purposes
Normally, a Java client would decide at runtime which ConcreteProgram to run
Net effect is that the start method of any ConcreteProgram can be invoked
Program is tested with: java AbstractDynamicProgram ConcreteProgram1
Hard-coded program:
class ConcreteProgram1 {
public void start() {
// beginning of code
}
}
(new ConcreteProgram1()).start();
Awkward solution (not easily extended to other classes):
class ConcreteProgram1 {
public void start() {
}
}
class ConcreteProgram2 {
public void start() {
}
}
switch (code) {
case 1: (new ConcreteProgram1()).start();
break;
case 2: (new ConcreteProgram2()).start();
break;
}
Dynamic Starter Pattern: Runtime Decision [55]
Main() provided programName to run
Class.forName() returns a Class
newInstance() returns an Object that can be cast as an AbstractDynamicProgram
All AbstractDynamicPrograms have a start() method, similar to a main()