1. 程式人生 > >枚舉類規範

枚舉類規範

pac () java ase nal pub new gree 註意

package junit;
/**
 * 枚舉類
 * @author pengYi
 *
 */
public class ColorEnum {
	
	private static final String CODE_RED = "1";
	private static final String CODE_YELLOW = "2";
	private static final String CODE_GREEN = "3";
	
	public static final ColorEnum RED = new ColorEnum(CODE_RED,"紅色");
	public static final ColorEnum YELLOW = new ColorEnum(CODE_YELLOW,"黃色");
	public static final ColorEnum GREEN = new ColorEnum(CODE_GREEN,"綠色");
	
	private String code;
	private String name;
	
	private ColorEnum(String code, String name) {
		this.code = code;
		this.name = name;
	}
	
	/**
	 * 返回枚舉類對象
	 * @param code
	 * @return
	 */
	public static ColorEnum getColorByCode(String code) {
		switch (code) {
			case CODE_RED : return RED;
			case CODE_YELLOW : return YELLOW;
			case CODE_GREEN : return GREEN;
			default : throw new IllegalArgumentException("請核對輸入參數");
		}
	}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getCode() {
		return code;
	}
	public void setCode(String code) {
		this.code = code;
	}
	
}

  需要註意是:構造方法是私有的,防止外部調用,保證枚舉類數據不被破壞

枚舉類規範