经常在源码阅读过程中,遇到一个状态标志位去标识多个状态,并对多状态进行控制的操作,下面是对多状态控制的一个总结:
public class Main {
public static final int SET_MOBILE = 0x1;
public static final int SET_SMS_CODE = 0x2;
public static final int SET_PASSWORD = 0x3;
public static final int REGISTER = 0x4;
public static Boolean isExistState(int currentSate, int targetSate) {
return (currentSate & targetSate) == targetSate;
}
public static int cancelState(int currentSate, int targetSate) {
return currentSate & ~targetSate;
}
public static void main(String[] args) {
// 设置mRegisterState 目前有3个状态
int mRegisterState = SET_MOBILE | SET_SMS_CODE | SET_PASSWORD;
System.out.println("===========初始化状态,包含 SET_MOBILE SET_SMS_CODE SET_PASSWORD======================");
System.out.println("存在状态SET_SMS_CODE : "+isExistState(mRegisterState, SET_SMS_CODE));
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
System.out.println("存在状态SET_PASSWORD : "+isExistState(mRegisterState, SET_PASSWORD));
System.out.println("=====================去除状态SET_SMS_CODE===========================");
mRegisterState = cancelState(mRegisterState, SET_SMS_CODE);
System.out.println("存在状态SET_SMS_CODE : "+isExistState(mRegisterState, SET_SMS_CODE));
System.out.println("===========================去除状态SET_PASSWORD======================");
mRegisterState &= ~SET_PASSWORD;
System.out.println("存在状态SET_PASSWORD : "+isExistState(mRegisterState, SET_PASSWORD));
System.out.println("===================添加状态REGISTER==================");
mRegisterState |= REGISTER;
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
System.out.println("===================“反转”操作:如果SET_SMS_CODE在组中,则从组中删除之;否则将SET_SMS_CODE加入组中==================");
mRegisterState ^= SET_SMS_CODE;
System.out.println("存在状态SET_SMS_CODE : "+isExistState(mRegisterState, SET_SMS_CODE));
System.out.println("==================清空所有状态=======================");
mRegisterState = 0;
System.out.println("存在状态SET_SMS_CODE : "+isExistState(mRegisterState, SET_SMS_CODE));
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
System.out.println("存在状态SET_PASSWORD : "+isExistState(mRegisterState, SET_PASSWORD));
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
System.out.println("==================添加所有状态=======================");
mRegisterState = ~0;
System.out.println("存在状态SET_SMS_CODE : "+isExistState(mRegisterState, SET_SMS_CODE));
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
System.out.println("存在状态SET_PASSWORD : "+isExistState(mRegisterState, SET_PASSWORD));
System.out.println("存在状态REGISTER : "+isExistState(mRegisterState, REGISTER));
}
}