Last active
December 29, 2015 12:19
-
-
Save rshepherd/7669949 to your computer and use it in GitHub Desktop.
An example of using a command object pattern.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Scanner; | |
public class CommandObject { | |
private static Scanner input = new Scanner(System.in); | |
// a stubbed out example of how you can use OO to clean up | |
// how you take user input from the user. | |
public static void main(String[] args) { | |
Command c = getCommand(); | |
while(!c.isQuit()) { | |
System.out.println(c); | |
// .. some other code here ... | |
c = getCommand(); | |
} | |
} | |
private static Command getCommand() { | |
Command cmd = new Command(); | |
System.out.print("Which car would you like to use?\n"); | |
cmd.setCar(input.next().charAt(0)); | |
System.out.println("What would you like to do?"); | |
System.out.println(" 1: Turn the ignition on/off."); | |
System.out.println(" 2: Change the position of car."); | |
System.out.println(" 3: Switch cars."); | |
System.out.println(" Q: Quit this program."); | |
cmd.setFunction(input.next().charAt(0)); | |
// etc.. | |
if(cmd.getFunction() == '2') { | |
System.out.print("How far (negative value to move left)?\n"); | |
cmd.setLeftOrRight(input.next().charAt(0)); | |
System.out.print("How far (negative value to move up)?\n"); | |
cmd.setUpOrDown(input.next().charAt(0)); | |
} // else if.. | |
// etc.. | |
return cmd; | |
} | |
// 'static' in this case means 'as if it were a class defined in another file' | |
// or more strictly speaking a 'top-level' class. Normal Java style is to not | |
// have more than one class in a file. I do it here for conciseness of the example. | |
public static class Command { | |
private char car; | |
private char function; | |
private char upOrDown; | |
private char leftOrRight; | |
public char getCar() { | |
return car; | |
} | |
public void setCar(char car) { | |
this.car = car; | |
} | |
public char getFunction() { | |
return function; | |
} | |
public void setFunction(char function) { | |
this.function = function; | |
} | |
public char getUpOrDown() { | |
return upOrDown; | |
} | |
public void setUpOrDown(char upOrDown) { | |
this.upOrDown = upOrDown; | |
} | |
public char getLeftOrRight() { | |
return leftOrRight; | |
} | |
public void setLeftOrRight(char leftOrRight) { | |
this.leftOrRight = leftOrRight; | |
} | |
public boolean isQuit() { | |
return function == 'Q'; | |
} | |
public String toString() { | |
return "Command{" + | |
"car=" + car + | |
", function=" + function + | |
", upOrDown=" + upOrDown + | |
'}'; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment