This was a team project in which myself and two other programmers wrote a command line interpreter for a military simulator in Java.

case "define":{
	switch(cmdArr[1]) {
		case "ship": builtCommand = CommandActorFactory.getActorCommand(managers, command); break;
		case "munition": builtCommand = CommandMunitionFactory.getCommandMunition(managers, command); break;
		case "sensor": builtCommand = CommandSensorFactory.getCommandSensor(managers, command); break;
		default: throw new RuntimeException("Invalid command input!");
	}
	break;
}

In order to handle all of the ways commands can branch, we used the factory design pattern to return the correct command object based on the rest of the command input.

// Factory Class
public class CommandMunitionFactory {
	
	public static A_CommandMunition getCommandMunition(CommandManagers managers, String command) {
		
		String[] cmdArr = command.split(" ", 0);
		A_CommandMunition cmdMunition = null;
		
		try {
			if (cmdArr[0].equals("define") && cmdArr[1].equals("munition")) {
				AgentID id = new AgentID(cmdArr[3]);
				switch (cmdArr[2]) {
				case "bomb": {
					cmdMunition = new CommandMunitionDefineBomb(managers, command, id); 
					break;
				}
				// ...
				default: throw new RuntimeException("Invalid Command");
				}
			}
		
		} catch (Exception e){
			throw new RuntimeException("Invalid Command");
		}
		
		return cmdMunition;
	}
}

By initializing the return variable as the generic “A_CommandMunition” type, I am using polymorphism to return one of a variety of Command types.

Back to Projects…