说明
问题的目的是实现一个接口,该接口将根据有关任务依赖性的信息对任务列表进行排序。例如,如果任务A依赖于任务B和C,则这意味着要开始处理任务A,必须首先完成任务B和C。我认为它应该像有向图结构。
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* The task class represents a certain activities that must be done as the part of the project planning
*/
class Task {
/**
* Unique name of the activity
*/
private String name;
/**
* A list of names of the activitiest that must be compelte in order to be able to start the current activity
*/
private List<String> predecessors;
public Task(String name, List<String> predecessors) {
this.name = name;
this.predecessors = predecessors;
}
public String getName() {
return name;
}
public List<String> getPredecessors() {
return predecessors;
}
}
接口应将任务列表(以任何顺序定义)作为输入参数,并输出按执行顺序排序的任务列表。
/**
* A scheduler interface is intended to process a random list of tasks with the information of their predecessors
* and return a list of the same tasks but in order they may be executed according to their dependencies
*/
interface IScheduler {
public List<Task> schedule(List<Task> tasks);
}
以下代码提供了如何使用该接口的示例。
public class Main {
public static void main(String[] args) {
/**
* The following is the example of how the scheduler may be used
*/
List<Task> tasks = Arrays.asList(
new Task("E", Arrays.asList("B")),
new Task("D", Arrays.asList("A", "B")),
new Task("A", Arrays.asList()),
new Task("B", Arrays.asList("A")),
new Task("C", Arrays.asList("D", "B")),
new Task("F", Arrays.asList("E"))
);
IScheduler scheduler = /* implementation here*/;
List<Task> sortedTasks = scheduler.schedule(tasks);
for (Task t: sortedTasks) {
System.out.println(t.getName());
}
}
}
问题
我如何实现对任务进行排序的界面?我需要使用JGraphT
或Guava Graph
之类的东西,还是有一些简单的方法?
据我所知,可以使用observer pattern解决您的问题>
观察者模式用于监视特定对象的状态,通常以组或一对多关系。在这种情况下,大多数情况下,单个对象的更改状态会影响其余对象的状态,因此必须有一个系统来记录更改并警告其他对象。
因此,当该对象的状态发生变化时,您可以执行或启动特定任务。