2019独角兽企业重金招聘Python工程师标准>>>
某种场景需要,一个事物 有多种状态并列存在的时候,或者权限,我们可以使用 |,&,~ 来处理,具体代码如下:
package com.example.demo;/*** 权限状态处理*/
public class StatusUtil {/*** 判断状态是否开启* @param flag* @param status* @return bool*/public static boolean isEnable(int flag, int status) {return (flag & status) == status;}/*** 判断状态是否关闭* @param flag* @param status* @return bool*/public static boolean isDisable(int flag, int status) {return (flag & status) == 0;}/*** 判断是否只有这个状态开启* @param flag* @param status* @return*/public static boolean isOnlyEnable(int flag, int status) {return flag == status;}/*** 添加状态* @param flag* @param status* @return*/public static int addStatus(int flag, int status) {return flag |= status;}/*** 扣除状态* @param flag* @param status* @return*/public static int deductStatus(int flag, int status) {return flag & ~status;}
}
package com.example.demo;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication
public class DemoApplication {// 初始public static final int init = 1 << 0;// 权限1public static final int power1 = 1 << 1;// 权限2public static final int power2 = 1 << 2;// 权限3public static final int power3 = 1 << 3;//权限4public static final int power4 = 1 << 4;public static void main(String[] args) {SpringApplication.run(DemoApplication.class, args);int status=init;//添加权限1status= StatusUtil.addStatus(status,power1);//判断是否具有权限1System.out.println( StatusUtil.isEnable(status,power1));//判断是否具有权限2System.out.println( StatusUtil.isEnable(status,power2));//添加权限2status= StatusUtil.addStatus(status,power2);//判断是否具有权限2System.out.println( StatusUtil.isEnable(status,power2));//解除权限1status= StatusUtil.deductStatus(status,power1);//判断是否具有权限1System.out.println( StatusUtil.isEnable(status,power1));//判断是否具有权限2System.out.println( StatusUtil.isEnable(status,power2));}
}