1つの変数に複数のステータスを格納



 
package mypacket;

public class Stage{

	static int stages = 0;
	/**
	 *  
	 * @param stage
	 */
	private static void setStage(int stage){
		stages |= stage;
	}
	/**
	 *  
	 * @param stage
	 * @return
	 */
	private static boolean isStage(int stage){
		return (stages & stage) != 0;
	}
	/**
	 *  
	 * @param stage
	 */
	private static void clearStage(int stage){
		stages =  (stages | stage) ^ stage;
	}
	public static void main(String[] args) {
		int stage0 = 1;
		int stage1 = 1 << 1;
		
		System.out.println("before set stage: stage0 is " + (isStage(stage0)? "" :"not ")  + "in the result.");
		System.out.println("before set stage: stage1 is " + (isStage(stage1)? "" :"not ")  + "in the result.");
		setStage(stage0);
		setStage(stage1);
		System.out.println("after set stage: stage0 is " + (isStage(stage0)? "" :"not ")  + "in the result.");
		System.out.println("after set stage: stage1 is " + (isStage(stage1)? "" :"not ")  + "in the result.");
		clearStage(stage0);
		System.out.println("after clear stage :stage0 is " + (isStage(stage0)? "" :"not ")  + "in the result.");
		
	}
}

これによりstagesという変数に複数の状態を保存することができ,実際の開発過程では,各状態を列挙タイプで存在させることを提案し,上記の設定,削除,判断の方法で伝達されたパラメータも列挙タイプに変更し,エラーを防止する.