Dynamic Switch statement using the Command Pattern [GOF]

/*
 * DynamicSwitch.java
 * @uthor martin@spamer.me.uk
 * Created on 23 March 2005, 13:41
 */
 
package uk.me.spamer.command;
 
/**
 * How to write a dynamic switch statement using the [GOF] command pattern.
 * @author  martin.spamer
 */
public class DynamicSwitch
  {
  public abstract class AbstractCase { public void execute() { System.err.println( this.getClass().getName() ) ; } } ;
  public class CaseAA extends AbstractCase { } ;
  public class CaseBB extends AbstractCase { } ;
  public class CaseCC extends AbstractCase { } ;
 
  java.util.HashMap cases = new java.util.HashMap() ;
 
  /** Creates a new instance of DynamicSwitch */
  public DynamicSwitch()
    {
    // load these names from a properties file 
    // and use a class factory to construct them.
    cases.put( "AA" ,new CaseAA() ) ;
    cases.put( "BB" ,new CaseBB() ) ;
    cases.put( "CC" ,new CaseCC() ) ;
    }
 
  public void execute(String key)
    {
    AbstractCase abstractCase = (AbstractCase) cases.get( key ) ;
    abstractCase.execute() ;
    }
 
  /**
   * @param args the command line arguments
   */
  public static void main(String[] args)
    {
    // TODO code application logic here
    DynamicSwitch instance = new DynamicSwitch() ;
 
    instance.execute( "AA" ) ;
    instance.execute( "BB" ) ;
    instance.execute( "CC" ) ;
    }
}

oo_java_dynamic_switch.txt ยท Last modified: 2013/01/30 18:01 by Martin Spamer