我正在开发的自制工作流框架为执行工作流所需调用的每个任务实例化一个类。更多的任务数量=更多的要创建的类数量。如何对此进行优化?我不想为每一项任务创建一个类。
例如。
Class MyWorkflow {
public List < Task > getTasks() {
return new ArrayList < Task > (
Arrays.asList(new Task1(),
new Task2(),
new Task3(),
)
);
}
}
最佳答案
如果支持一项常规任务过于通用,则可能有一个任务,或者至少有几个定义的任务类。 Varargs 允许您根据操作的需要传递实体 ID 等。或者传递 Employee.class 而不是对象?
public class TaskRunner {
public List <Task> getTasks() {
return new ArrayList <Task> (
Arrays.asList(new Task(new Employee(), TaskOperation.Delete, "10"),
new Task(new Employee(), TaskOperation.Retrieve, "15")
)
);
}
}
public enum TaskOperation {
Create,
Delete,
Update,
Retrieve;
}
public class Task implements Runnable {
private final Object entity;
private final TaskOperation operation;
public Task(Object entity, TaskOperation operation, String... args) {
super();
this.entity = entity;
this.operation = operation;
}
@Override
public void run() {
// EmployeeDAO employeeDAO = ...
if (entity instanceof Employee) {
switch(operation) {
case Create:
// Perform Create on Employee
// Employee e = new Employee();
// employeeDAO.create(...);
break;
case Delete:
// Perform Delete on Employee
break;
}
// ....
}
}
}
关于工作流引擎的Java实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34687605/