使用位运算设计权限

使用位运算设计权限

  • 假设我们有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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值