位运算设计一个字段表示多个状态

写在前面

位运算来设计权限字段,使用一个字段,就可以表示多种含义,比如权限字段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类

内部采用此模式。

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值