写在前面
位运算来设计权限字段,使用一个字段,就可以表示多种含义,比如权限字段authority,该字段有多种状态,比如查询、新增、修改、删除等。
代码实现
public class Authority {
public static final int ALLOW_SELECT = 1 << 0; //0001 1
public static final int ALLOW_UPDATE = 1 << 1; //0010 2
public static final int ALLOW_INSERT = 1 << 2; //0100 4
public static final int ALLOW_DELETE = 1 << 3; //1000 8
public static final int ALL_AUTHORITY = 15; //所有权限
private int authority;
/**
* 设置权限
*/
public void setAuthority(int authority) {
this.authority = authority;
}
/**
* 新增权限,可多选
*/
public void enable(int authority) {
this.authority = this.authority | authority;
}
/**
* 删除权限,可多选
*/
public void disable(int authority) {
this.authority = this.authority & (~authority);
}
/**
* 判断是否存在某个权限,可多选
*/
public boolean isAllow(int authority) {
return (this.authority & authority) == authority;
}
/**
* 判断是否不存在某个权限,可多选
*/
public boolean isNotAllow(int authority) {
return (this.authority & authority) == 0;
}
public static void main(String[] args) {
Authority authority = new Authority();
//设置所有权限 方式1
//authority.setAuthority(ALL_AUTHORITY);
//设置所有权限 方式2
authority.enable(ALLOW_SELECT | ALLOW_INSERT | ALLOW_UPDATE | ALLOW_DELETE);
//删除查询条件
authority.disable(ALLOW_SELECT);
//删除 修改权限 和 删除权限
authority.disable(ALLOW_UPDATE | ALLOW_DELETE);
if (authority.isAllow(ALLOW_DELETE)) {
//如果有删除权限,完成删除业务
}
if (authority.isAllow(ALLOW_UPDATE)) {
//如果有修改权限,完成删除业务
}
}
}
参考jdk1.8 Modifier类
内部采用此模式。