Define an array (or Map, or ENUM) of functions

From CodeCodex

Implementations[edit]

Java[edit]

Using an interface First we define an interface.

 public interface Command {
  void exec();
}

then the implementation of the functions

 public class ACommandImpl implements Command {
  @Override
  public void exec() {
    System.out.println("This is Command type A");
  }
}
 public class BCommandImpl implements Command {
  @Override
  public void exec() {
    System.out.println("This is Command type B");
  }
}
 public class CCommandImpl implements Command {
  @Override
  public void exec() {
    System.out.println("This is Command type C");
  }
}

We put in an array an instance of each implementation. Then we are able to run the desired function by using the array index.

 public class TestCommand {
  public static void main(String[] args) {
    Command[] commands = new Command[3];
    commands[0] = new ACommandImpl();
    commands[1] = new BCommandImpl();
    commands[2] = new CCommandImpl();
    // no error checking!
    for (;;) {
      String s = javax.swing.JOptionPane.showInputDialog
          ("Command no ? (0,1 or 2)", new Integer(0));
      if (s == null) break;
      commands[Integer.parseInt(s)].exec();
    }
  }
}

To use a String instead of a number to access to desired function, use a Map.

 public class TestCommand {
  public static void main(String[] args) {
    java.util.Map <String, Command> commands = 
      new java.util.HashMap<String, Command>(); 
    commands.put("A", new ACommandImpl());
    commands.put("B", new BCommandImpl());
    commands.put("C", new CCommandImpl());
    // no error checking!
    for (;;) {
      String s = javax.swing.JOptionPane.showInputDialog
        ("Command ID ? (A,B or C)", "A");
      if (s == null) break;
      commands.get(s.toUpperCase()).exec();
    }
  }
}

Using an enum

 public interface Command {
  void exec();
}
 enum Functions implements Command {
  A() {
    public void exec() {
      System.out.println("This is Command type A");
    }
  },
  B() {
    public void exec() {
      System.out.println("This is Command type B");
    }
  },
  C() {
    public void exec() {
      System.out.println("This is Command type C");
    }
  }
}

then

 public class TestCommand {
  public static void main(String[] args) {
    // no error checking!
    for (;;) {
      String s = javax.swing.JOptionPane.showInputDialog
        ("Command ID ? (A,B or C)", "A");
      if (s == null) break;
      Functions function = Functions.valueOf(s.toUpperCase());
      function.exec();
    }
  }
}

NOTE : Using this technique, it's possible to simulate "switch ... case" based on a string value.