Tasks之间共享TaskKey,哪个更好?还有其他更好的方法吗?
way1 通过一个关键对象共享。这样,客户端代码(任务队列)更容易编写配置任务表。但是每个任务都必须浪费内存来存储 TaskKey 对象。
class TaskKey {
int key1;
int key2;
// key3...
TaskKey(int key1, int key2) {
this.key1 = key1;
this.key2 = key2;
}
}
abstract class Task implements Cloneable {
TaskKey key;
int taskData;
Task(TaskKey key) {
this.key = key;
}
int getKey1() {
return key.key1;
}
int getKey2() {
return key.key2;
}
Task newInstance(int taskData) {
Task task = (Task) clone();
task.taskData = taskData;
return task;
}
abstract void doSomething();
}
class TaskQueue {
Task[][] taskTable;
void addTask(Task task) {
taskTable[task.getKey1()][task.getKey2()] = task;
}
void config() {
addTask(new Task(new TaskKey(1, 1)) {
void doSomething() {}
});
addTask(new Task(new TaskKey(1, 2)) {
void doSomething() {}
});
addTask(new Task(new TaskKey(2, 1)) {
void doSomething() {}
});
}
Queue<Task> queue;
void put(int key1, int key2, int taskData) {
Task task = taskTable[key1][key2];
queue.add(task.newInstance(taskData));
}
}
way2 由任务类共享。这样,客户端代码(任务队列)写配置任务表很麻烦(重写任务的getKey()方法)。但是每个任务都不需要浪费内存来存储TaskKey对象,因为关键信息是由具体的Task类共享的。
abstract class Task implements Cloneable {
int taskData;
abstract int getKey1();
abstract int getKey2();
abstract void doSomething();
Task newInstance(int taskData) {
Task task = (Task) clone();
task.taskData = taskData;
return task;
}
}
class TaskQueue {
Task[][] taskTable;
void addTask(Task task) {
taskTable[task.getKey1()][task.getKey2()] = task;
}
void config() {
addTask(new Task() {
int getKey1() { return 1; }
int getKey2() { return 1; }
void doSomething() {}
});
addTask(new Task() {
int getKey1() { return 1; }
int getKey2() { return 2; }
void doSomething() {}
});
addTask(new Task() {
int getKey1() { return 2; }
int getKey2() { return 1; }
void doSomething() {}
});
}
Queue<Task> queue;
void put(int key1, int key2, int taskData) {
Task task = taskTable[key1][key2];
queue.add(task.newInstance(taskData));
}
}
另一种方式1和方式2
interface TaskExecutor {
void exec(Task task);
}
class TaskKey {
int key1;
int key2;
int key3;
TaskExecutor executor;
}
class Task /*another way1*/ {
TaskKey key;
int taskData;// in fact it is not only a int
int getKey1() { // because i need to retrieve key1 from a task
return key.key1;
}
// also get methods for key2 key3
void exec(){
key.executor.exec(this);
}
}
class Task /*another way2*/ {
public final int key1;
public final int key2;
public final int key3;
private final TaskExecutor executor;
int taskData;
void exec(){
executor.exec(this);
}
}