位运算的运用-权限控制:add,query,modify,del

位运算的运用-权限控制:add,query,modify,del

public class Permission {

    private static final int ALLOW_SELECT = 1<<0;//0001
    private static final int ALLOW_INSERT = 1<<1;//0010
    private static final int ALLOW_UPDATE = 1<<2;//0100
    private static final int ALLOW_DELETE = 1<<3;//1000

    //当前的权限状态
    private int flag;

    public void setPermission(int permission){
        flag = permission;
    }


    /*增加权限,可以一项或者多项*/
    public void addPermission(int permission){
        flag = flag|permission;
    }

    /*删除权限,可以一项或者多项*/
    public void disablePermission(int permission){
        flag = flag&~permission;
    }

    /*是否拥有某些权限*/
    public boolean isAllowed(int permission){
        return (flag&permission)==permission;
    }

    /*是否不拥有某些权限*/
    public boolean isNotAllowed(int permission){
        return (flag&permission)==0;
    }


    public static void main(String[] args) {
		int flag = 15;//1111
		Permission permission = new Permission();
		permission.setPermission(flag);
		permission.disablePermission(ALLOW_DELETE|ALLOW_INSERT);
		System.out.println("ALLOW_SELECT="+permission.isAllowed(ALLOW_SELECT));
		System.out.println("ALLOW_INSERT="+permission.isAllowed(ALLOW_INSERT));
		System.out.println("ALLOW_UPDATE="+permission.isAllowed(ALLOW_UPDATE));
		System.out.println("ALLOW_DELETE="+permission.isAllowed(ALLOW_DELETE));
	}
}

结果:

ALLOW_SELECT=true
ALLOW_INSERT=false
ALLOW_UPDATE=true
ALLOW_DELETE=false

jdk里的NIO里的OP_WRITE、OP_READ等也是用的这种思想。

发布了131 篇原创文章 · 获赞 233 · 访问量 1万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 撸撸猫 设计师: 设计师小姐姐

分享到微信朋友圈

×

扫一扫,手机浏览