next up previous contents
Next: Abstract Factory Pattern: Platform Up: Patterns Previous: Singleton Pattern: One Global   Contents

Dynamic Starter Pattern: Runtime Decision [54]



$\bullet$ Problem: How to decide at runtime which program to execute (e.g. user types in string name)?

$\bullet$ Solution: Dynamic Starter Pattern

$\bullet$ 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.

$\bullet$ UML is shown for #1 (which means ConcreteProgram1), but should be able to work for any number of ConcretePrograms

$\bullet$ Main() call is just used for testing purposes

$\bullet$ Normally, a Java client would decide at runtime which ConcreteProgram to run

$\bullet$ Net effect is that the start method of any ConcreteProgram can be invoked

$\bullet$ 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]


\begin{picture}(330,220)(55,600)\thicklines
\put( 55,600){\framebox (115,40){...
...
\put(220,660){\line( 1, 0){105}}
\put(325,660){\line( 0,-1){ 20}}
\end{picture}




\begin{picture}(610,250)(15,570)\thicklines
\put(100,660){\framebox (160,40){...
...){\makebox(0,0)[lb]{\raisebox{0pt}[0pt][0pt]{\twlrm 1.3:start()}}}
\end{picture}



$\bullet$ Main() provided programName to run

$\bullet$ Class.forName() returns a Class

$\bullet$ newInstance() returns an Object that can be cast as an AbstractDynamicProgram

$\bullet$ All AbstractDynamicPrograms have a start() method, similar to a main()


next up previous contents
Next: Abstract Factory Pattern: Platform Up: Patterns Previous: Singleton Pattern: One Global   Contents
Ted Billard 2006-09-26