1.常规判断
package com.if_else;
/**
* @Description:管理员a有A权限,管理员b有B权限,管理员c有C权限,一般获取权限判断如下
* @Author: Tgy
* @Date: 2019/12/23 15:06
**/
public class DoMain1 {
public static void main(String[] args) {
String power=judge("a");
System.out.println(power);
}
public static String judge(String role){
if(role.equals("a")){
return "A";
}else if(role.equals("b")){
return "B";
}else if(role.equals("c")){
return "C";
}else {
return null;
}
}
}
2.用枚举进行判断
package com.if_else;
/**
* @Description:管理员a有A权限,管理员b有B权限,管理员c有C权限,用枚举判断权限
* @Author: Tgy
* @Date: 2019/12/23 15:22
**/
public class DoMain2 {
public static void main(String[] args) {
System.out.println(judge("a"));
}
public static String judge(String role){
return RoleEnum.valueOf(role).op();
}
}
package com.if_else;
/**
* @Description:
* @Author: Tgy
* @Date: 2019/12/23 15:24
**/
public enum RoleEnum implements RoleOperation{
a{
@Override
public String op() {
return "A";
}
},
b{
@Override
public String op() {
return "B";
}
},
c{
@Override
public String op() {
return "C";
}
};
}
3.用工厂模式代替判断
package com.if_else;
/**
* @Description:管理员a有A权限,管理员b有B权限,管理员c有C权限,用工厂模式获取权限
* @Author: Tgy
* @Date: 2019/12/23 15:29
**/
public class DoMain3 {
public static void main(String[] args) {
System.out.println(judge("a"));
}
public static String judge(String roleName){
return RoleFactory.getOp(roleName).op();
}
}
package com.if_else;
public interface RoleOperation {
String op();//表示某个角色可以有哪些权限
}
package com.if_else;
/**
* @Description:管理员a有A权限
* @Author: Tgy
* @Date: 2019/12/23 15:31
**/
public class UserARole implements RoleOperation {
private String roleName;
public UserARole(String roleName) {
this.roleName = roleName;
}
@Override
public String op() {
return "A";
}
}
package com.if_else;
/**
* @Description:管理员b有B权限
* @Author: Tgy
* @Date: 2019/12/23 15:31
**/
public class UserBRole implements RoleOperation {
private String roleName;
public UserBRole(String roleName) {
this.roleName = roleName;
}
@Override
public String op() {
return "B";
}
}
package com.if_else;
/**
* @Description:管理员c有C权限
* @Author: Tgy
* @Date: 2019/12/23 15:31
**/
public class UserCRole implements RoleOperation {
private String roleName;
public UserCRole(String roleName) {
this.roleName = roleName;
}
@Override
public String op() {
return "C";
}
}
package com.if_else;
import java.util.HashMap;
import java.util.Map;
/**
* @Description:工厂类,对角色进行聚合
* @Author: Tgy
* @Date: 2019/12/23 15:33
**/
public class RoleFactory {
static Map<String,RoleOperation> roleOperationMap=new HashMap<>();
//在静态块中先比初始化工作全部做完
static {
roleOperationMap.put("a",new UserARole("a"));
roleOperationMap.put("b",new UserARole("b"));
roleOperationMap.put("c",new UserARole("c"));
}
public static RoleOperation getOp(String roleName){
return roleOperationMap.get(roleName);
}
}