Define an array (or Map, or ENUM) of functionsTag(s): Language
Using an interface
First we define an interface.public interface Command { void exec(); }
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"); } }
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(); } } }
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"); } } }
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(); } } }
mail_outline
Send comment, question or suggestion to howto@rgagnon.com
Send comment, question or suggestion to howto@rgagnon.com