close
一般定義常數方式如下:
public class Robot {
    public static final int COMMAND_WALK = 0;
    public static final int COMMAND_STOP = 1;
    public static final int COMMAND_JUMP = 2;
}
比較時是使用int為input參數:
public void order (int command) {
    if (command == COMMAND_WALK) {
    } else if (command == COMMAND_STOP) {
    } else if (command == COMMAND_JUMP) {
    } else {
    }
}
 
以下是JDK 1.4以下用Class的替代方案:
public class RobotCommand {
    private final String _name;
    public RobotCommand (String name) { _name=name; }
    public String toString() { return "[RobotCommand: " + _name + "]"; }
}
比較時是使用RobotCommand 為input參數:
    public static final RobotCommand COMMAND_WALK = new RobotCommand("WALK");
    public static final RobotCommand COMMAND_STOP = new RobotCommand("STOP");
    public static final RobotCommand COMMAND_JUMP = new RobotCommand("JUMP");
public void order (RobotCommand command) {
    if (command == COMMAND_WALK) {
    } else if (command == COMMAND_STOP) {
    } else if (command == COMMAND_JUMP) {
    } else {
    }
}
 
以下是JDK 5.0以上用Enum的替代方案:
public class Robot {
    public enum Command {
        WALK,
        STOP,
        JUMP,
    };
}
 
比較時是使用Robot.Command 為input參數:(outter.inner)
public void order (Robot.Command command) {
    if (command == Robot.Command.WALK) {
    } else if (command == Robot.Command.STOP) {
    } else if (command == Robot.Command.JUMP) {
    } else {
    }
}
arrow
arrow
    全站熱搜
    創作者介紹
    創作者 Jemmy 的頭像
    Jemmy

    Jemmy Walker

    Jemmy 發表在 痞客邦 留言(0) 人氣()