if else 代码优化实战
前言
介绍几种方法,不使用if else语句也能做条件判断。
一:使用枚举
首先定义一个公用接口 RoleOperation,表示不同角色所能做的操作
package com.gavin.enums;
public interface RoleOperation {
//定义一个方法来表示某个角色,有哪些op(操作)权限
String op();
}
接下来我们将不同角色的情况全部交由枚举类来做,定义一个不同角色有不同权限的枚举类
package com.gavin.enums;
public enum RoleEnum implements RoleOperation{
//定义一个超级管理员的操作权限(有AAA的操作权限)
ROLE_ROOT_ADMIN {
@Override
public String op() {
return "ROLE_ROOT_ADMIN:has AAA permission";
}
},
//定义一个订单管理员的操作权限(有BBB的操作权限)
ROLE_ORDER_ADMIN {
@Override
public String op() {
return "ROLE_ORDER_ADMIN:has BBB permission";
}
},
//定义一个普通用户的操作权限(有CCC的操作权限)
ROLE_NORMAL {
@Override
public String op() {
return "ROLE_NORMAL:has CCC permission";
}
};
}
一行代码,if/else也灰飞烟灭了
package com.gavin.enums;
public class JudgeRole {
public static void main(String[] args) {
String roleName = "ROLE_ROOT_ADMIN";
String operation = RoleEnum.valueOf(roleName).op();
System.out.println("操作权限:" + operation);
}
}
以后扩充条件,只需要去枚举类中加代码即可
。
二:使用工厂模式
不同分支做不同的事情,很明显就提供了使用工厂模式的契机,我们只需要将不同情况单独定义好,然后去工厂类里面聚合即可。
首先,针对不同的角色,单独定义其业务类:
package com.gavin.factory;
import com.gavin.enums.RoleOperation;
public class RootAdminRole implements RoleOperation {
//定义属性值
private String roleName;
//有参构造方法
public RootAdminRole (String roleName) {
this.roleName = roleName;
}
//实现RoleOperation接口,然后重写接口方法
@Override
public String op() {
return roleName + " has AAA permission";
}
}
package com.gavin.factory;
import com.gavin.enums.RoleOperation;
public class OrderAdminRole implements RoleOperation {
//定义属性值
private String roleName;
//有参构造方法
public OrderAdminRole(String roleName) {
this.roleName = roleName;
}
//实现RoleOperation接口,然后重写接口方法
@Override
public String op() {
return roleName + " has BBB permission";
}
}
package com.gavin.factory;
import com.gavin.enums.RoleOperation;
public class NormalRole implements RoleOperation {
//定义属性值
private String roleName;
//有参构造方法
public NormalRole(String roleName) {
this.roleName = roleName;
}
//实现RoleOperation接口,然后重写接口方法
@Override
public String op() {
return roleName + " has CCC permission";
}
}
接下来再写一个工厂类 RoleFactory对上面不同角色进行聚合:
package com.gavin.factory;
import com.gavin.enums.RoleOperation;
import java.util.HashMap;
import java.util.Map;
public class RoleFactory {
//定义一个Map集合,使用static修饰后会与类一起加载进堆中
//加载顺序早于没有用static修饰的常量、变量和方法
static Map<String, RoleOperation> map = new HashMap<>();
//定义一个静态方法进行初始化
static {
map.put("ROLE_ROOT_ADMIN", new RootAdminRole("ROLE_ROOT_ADMIN"));
map.put("ROLE_ORDER_ADMIN", new OrderAdminRole("ROLE_ORDER_ADMIN"));
map.put("ROLE_NORMAL", new NormalRole("ROLE_NORMAL"));
}
//定义一个获取操作权限的静态方法,提供给其它方法调用
public static RoleOperation getOp(String roleName) {
return map.get(roleName);
}
}
接下来借助上面这个工厂,业务代码调用也只需一行代码:
package com.gavin.factory;
public class JudgeRole02 {
public static void main(String[] args) {
/**
* 使用工厂模式实现思路,先调用RoleFactory类中的getOp方法,找到对应的角色对象中的权限
* 再调用该对象中的op()方法获取角色的权限信息
*/
String roleName = "ROLE_ROOT_ADMIN";
String operation = RoleFactory.getOp(roleName).op();
System.out.println("操作权限:" + operation);
}
}
扩展条件也很容易,只需要增加新代码,而不需要动以前的业务代码,非常符合“开闭原则”。
三:使用策略模式
策略模式和工厂模式写起来其实区别也不大!
在上面工厂模式代码的基础上,按照策略模式的指导思想,我们也来创建一个所谓的策略上下文类,这里命名为 RoleContext:
package com.gavin.strategy;
import com.gavin.enums.RoleOperation;
public class RoleContext {
//定义可更换的策略,传入不同的策略对象,业务即相应变化
private RoleOperation roleOperation;
public RoleContext(RoleOperation roleOperation) {
this.roleOperation = roleOperation;
}
//定义获取角色权限的方法
public String execute() {
return roleOperation.op();
}
}
很明显上面传入的参数 operation就是表示不同的“策略”。我们在业务代码里传入不同的角色,即可得到不同的操作结果:
package com.gavin.strategy;
import com.gavin.enums.RoleOperation;
import com.gavin.factory.NormalRole;
import com.gavin.factory.OrderAdminRole;
import com.gavin.factory.RootAdminRole;
public class JudgeRole03 {
public static void main(String[] args) {
JudgeRole03 judgeRole03 = new JudgeRole03();
String operation = judgeRole03.judge(new RootAdminRole("ROLE_ROOT_ADMIN"));
System.out.println("operation=" + operation);
String operation2 = judgeRole03.judge(new OrderAdminRole("ROLE_ORDER_ADMIN"));
System.out.println("operation2=" + operation2);
String operation3 = judgeRole03.judge(new NormalRole("ROLE_NORMAL"));
System.out.println("operation3=" + operation3);
}
//定义一个方法来调用RoleContext对象中获取角色权限的execute()方法
public String judge(RoleOperation roleOperation) {
RoleContext roleContext = new RoleContext(roleOperation);
return roleContext.execute();
}
}
几种常用的if else语句的优化方法,写代码前还是得多思考一番,考虑是否有更具可扩展性的写法!
四:实战应用
用枚举扩展实战
public class PublicEvent extends ProcessPubicListener {
/**
* 全局流程监听事件
* @param eventName
* @param taskInstance
* @param processExecutionContext
*/
@Override
public void call(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
PublicOperationEnum.valueOf(eventName).pOperation(eventName,taskInstance,processExecutionContext);
System.out.println("操作流程是:" + "------======------ ------======------");
}
}
定义接口:
public interface ProcessOperation {
//定义一个方法来表示某个流程,有哪些(操作)
void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext);
}
定义枚举:
public enum PublicOperationEnum implements ProcessOperation {
PROCESS_BEFORE_RESTART{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processBeforeRestart(eventName,processExecutionContext);
}
},
TASK_DELEGATE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.taskDelegate(eventName,taskInstance,processExecutionContext);
}
},
TASK_READ{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.taskRead(eventName,taskInstance);
}
},
PROCESS_CREATE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processCreate(eventName,processExecutionContext);
}
},
TASK_CREATE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.taskCreate(eventName,taskInstance,processExecutionContext);
}
},
PROCESS_BEFORE_DELETE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processBeforeDelete(eventName,taskInstance,processExecutionContext);
}
},
TASK_DELETE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.taskDelete(eventName,taskInstance,processExecutionContext);
}
},
PROCESS_DELETE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processDelete(eventName,taskInstance,processExecutionContext);
}
},
PROCESS_REMIND{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processRemind(eventName,taskInstance,processExecutionContext);
}
},
PROCESS_UPDATE{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processUpdate(eventName,taskInstance);
}
},
PROCESS_RESTART{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processRestart(eventName,taskInstance,processExecutionContext);
}
},
PROCESS_EVENT_END{
@Override
public void pOperation(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
ProcessTask.processEventEnd(eventName,taskInstance,processExecutionContext);
}
};
}
定义流程任务:
public class ProcessTask {
public static void processEventEnd(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到[" + eventName + "]" + taskInstance);
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--[" + eventName + "]" +",结束!");
}
public static void processRestart(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:流程重置事件[" + eventName + "]" + taskInstance);
System.out.println("此时,任务实例是空的!");
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--流程重置,结束!");
}
public static void processUpdate(String eventName, TaskInstance taskInstance) {
System.out.println("--我监听到:流程修改事件[" + eventName + "]" + taskInstance);
System.out.println("此时,任务实例,流程实例都是是空的!");
System.out.println("--流程修改,结束!");
}
public static void processRemind(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:流程催办[" + eventName + "]" + taskInstance);
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--流程催办,结束!");
}
public static void processDelete(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:流程实例删除后[" + eventName + "]" + taskInstance);
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--流程实例删除后,结束!");
}
public static void taskDelete(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:任务删除[" + eventName + "]" + taskInstance);
if(taskInstance==null){//当任务实例为空的时候是真删除,像流程撤销、流程实例删除
List<HistoryTaskInstance> deleteTaskList = (List<HistoryTaskInstance> )processExecutionContext.getParameter("taskList");
System.out.println("输出TASK_DELETE删除的已办任务实例(此处获取的删除任务列表是流程撤消前和流程删除前获取的总和)");
for(TaskInstance htask:deleteTaskList){
System.out.println("删除taskInstID为::"+htask.getId());
}
System.out.println("此时是真删除,像流程撤销、流程实例删除,流程实例、任务实例都是空的!");
}else{//当任务实例是非空,那么就是假删除,像流程提交
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("此时是假删除,像流程提交,流程实例、任务实例都是空的!");
}
System.out.println("--任务删除,结束!");
}
public static void processBeforeDelete(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:流程实例删除前[" + eventName + "]" + taskInstance);
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
List<TaskInstance> tasks = SDK.getTaskQueryAPI().processInstId(processInstID).list();
System.out.println("输出删除前要删除的任务实例:");
for(TaskInstance task:tasks){
System.out.println("删除taskInstID为::"+task.getId());
}
List<HistoryTaskInstance> Historytasks = SDK.getHistoryTaskQueryAPI().processInstId(processInstID).list();
System.out.println("输出删除前要删除的已办任务实例");
for(TaskInstance htask:Historytasks){
System.out.println("删除taskInstID为::"+htask.getId());
}
System.out.println("流程实例::"+processInstID+"::状态:"+processState);
System.out.println("--流程实例删除前,结束!");
}
public static void taskCreate(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:任务实例创建[" + eventName + "]" + taskInstance);
System.out.println("任务节点信息为:"+taskInstance.getActivityDefId());
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--任务实例创建,结束!");
}
public static void processCreate(String eventName, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到流程实例创建[" + eventName + "]" );
System.out.println("此时,任务实例是空的!");
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--流程实例创建,结束!");
}
public static void taskRead(String eventName, TaskInstance taskInstance) {
System.out.println("--我监听到:任务阅读[" + eventName + "]" + taskInstance);
System.out.println("--任务阅读,结束!");
}
public static void taskDelegate(String eventName, TaskInstance taskInstance, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:任务转办[" + eventName + "]" + taskInstance);
System.out.println("转办人:"+taskInstance.getOwner());
String processInstID = processExecutionContext.getProcessInstance().getId();
String processState = processExecutionContext.getProcessInstance().getControlState();
Map<String,Object> parameters = processExecutionContext.getParameters();
if(parameters.containsKey("OLD_TASKINST")){
//获取转办前的执行人
TaskInstance oldtaskinst = (TaskInstance) parameters.get("OLD_TASKINST");
System.out.println("接收人:"+oldtaskinst.getTarget());
}
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--任务转办,结束!");
}
public static void processBeforeRestart(String eventName, ProcessExecutionContext processExecutionContext) {
System.out.println("--我监听到:流程撤销前[" + eventName + "]");
System.out.println("此时,任务实例是空的!");
String processInstID = processExecutionContext.getProcessInstance().getId();
System.out.println("流程实例ID为["+processInstID+"]");
processExecutionContext.getProcessInstance().getControlState();
String processState = processExecutionContext.getProcessInstance().getControlState();
List<TaskInstance> tasks = SDK.getTaskQueryAPI().processInstId(processInstID).list();
System.out.println("输出撤消前要删除的待办任务实例");
for(TaskInstance task:tasks){
System.out.println("删除taskInstID为::"+task.getId());
}
List<HistoryTaskInstance> Historytasks = SDK.getHistoryTaskQueryAPI().processInstId(processInstID).list();
System.out.println("输出撤消前要删除的已办任务实例");
for(TaskInstance htask:Historytasks){
System.out.println("删除taskInstID为::"+htask.getId());
}
String processTitle=processInstID+processExecutionContext.getProcessInstance().getTitle();
System.out.println("流程实例::"+processTitle+"["+processInstID+"]::状态:"+processState);
System.out.println("--流程撤销前,结束!");
}
}