java权限设计思路之一

package com.hety.auth;


/**
 * 
 * 
 * @author hety
 * @version 1.0 2015-6-9 下午2:27:06
 */
public class AuthTest {


public static void main(String[] args) {

/*
* 如果用户有权限:添加A---2;删除B---3;修改B---4
那用户的权限值 purview =2^2+2^3+2^4=28,也就是2的权的和了。
化成二进制可以表示为11100
这样,如果要验证用户是否有删除B的权限,就可以通过位与运算来实现。
在Java里,位与运算运算符号为&
即是:int value = purview &((int)Math.pow(2,3));
*/

    /**
     *
     * @param totalPower 总权限
     * @param currentPower 当前权限
     * @return true 拥有此optPurview权限,反之亦然。
     */
    public static boolean checkPower(int totalPower, int currentPower) {
//        int purviewValue = (int) Math.pow(2, currentPower);
        int purviewValue = 1 << currentPower;
        return (totalPower & purviewValue) == purviewValue;
    }


    public static void main(String[] args) {
        System.out.println("1 << 1  ="+(1 << 1));
        System.out.println("1 << 2  ="+(1 << 2));
        System.out.println("1 << 3  ="+(1 << 3));
        int test =0;
//        int c = ( ((1 << 1)+(1 << 2)+(1 << 3)+(1 << 4)) );
        int c =  (1 << 1) + (1 << 2) + (1 << 3) + (1 << 4) ;
        System.out.println("2^1+2^2+2^3+2^4="+c);
        boolean e = checkPower(c, test);
        System.out.println(test +"是否具有"+c+"中的权限:"+e );
        int tempStatus = (1 << 1 )+ (1 << 3);
        System.out.println(tempStatus);

        int tempStatus2 = ((1 << 1) + (1 << 3));
        System.out.println(tempStatus2);
    }

}

// 权限计算:2^1 + 2^2 + 2^3 + 2^4
const c = (2 ** 1) + (2 ** 2) + (2 ** 3) + (2 ** 4);
console.log(`2^1+2^2+2^3+2^4=${c}`);

const test = 11; // 要检查的操作权限(注意:这里 test=11 是一个很大的位,通常权限位不会这么大)
const e = checkPower(c, test);
console.log("auth: " + e);

/**
 * 检查用户是否具有指定权限
 * @param {number} userPurview - 用户拥有的总权限值(位掩码)
 * @param {number} optPurview - 要检查的操作权限位(例如 3 表示删除B)
 * @returns {boolean} 是否拥有该权限
 */
function checkPower(userPurview, optPurview) {
    const purviewValue = 2 ** optPurview; // 等价于 1 << optPurview
    return (userPurview & purviewValue) === purviewValue;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值