文章目录
使用位运算设计权限
- 假设我们有4中权限,我们用二进制来表示,四位的二进制对应四种权限,对应位置上0表示没有权限,1表示有权限,这样在权限比较多的时候设计就会带来比较大的便利,如果本身权限的类型比较少,这样的便利体现的不那么明显;
/**
* @author by mozping
* @Classname Permission
*/
public class Permission {
int flag;
public static final int ADD_PERMISSION = 1 << 0;
public static final int DEL_PERMISSION = 1 << 1;
public static final int MODIFY_PERMISSION = 1 << 2;
public static final int QUERY_PERMISSION = 1 << 3;
//设置权限
public void setPer(int per) {
flag = per;
}
//增加权限
public void addPer(int per) {
flag = flag | per;
}
//删除权限
public void delPer(int per) {
flag = flag & ~per;
}
//获取权限
public int getPer() {
return flag;
}
//判断是否有指定权限
public boolean isAllowPer(int per) {
return (flag & per) == per;
}
public static void main(String[] args) {
Permission permission = new Permission();
permission.setPer(15);
System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
System.out.println("---------------------------");
permission.delPer(ADD_PERMISSION | DEL_PERMISSION);
System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
permission.addPer(ADD_PERMISSION);
System.out.println("---------------------------");
System.out.println("add permission:" + permission.isAllowPer(ADD_PERMISSION));
System.out.println("del permission:" + permission.isAllowPer(DEL_PERMISSION));
System.out.println("modify permission:" + permission.isAllowPer(MODIFY_PERMISSION));
System.out.println("query permission:" + permission.isAllowPer(QUERY_PERMISSION));
System.out.println("---------------------------");
System.out.println(permission.isAllowPer(QUERY_PERMISSION));
}
}
输出:
add permission:true
del permission:true
modify permission:true
query permission:true
---------------------------
add permission:false
del permission:false
modify permission:true
query permission:true
---------------------------
add permission:true
del permission:false
modify permission:true
query permission:true
---------------------------
true