嗯好的,廣東話混合牛奶和咖啡在我的杯子
由於觀察點模式的超重在這裏,我用我自己的嘗試。
不知何故咖啡或牛奶不放在杯子裏。
package test;
import java.util.*;
public class Task extends Thread {
private static final Task EMPTY_TASK = null;
private Task postTask = EMPTY_TASK;
private final List<Task> preconditions;
public Task() {
super();
preconditions = Collections.emptyList();
}
public Task(final String name, final Task... preliminaries) {
super(name);
this.preconditions = new ArrayList<Task>(Arrays.asList(preliminaries));
for (Task preliminary : preliminaries) {
preliminary.setPostTask(this);
}
}
private void setPostTask(final Task postTask) {
this.postTask = postTask;
}
@Override
public void run() {
System.out.println("Working " + this);
if (postTask != null) {
postTask.informSolved(this);
}
}
@Override
public synchronized void start() {
if (preconditions.size() == 0) {
super.start();
} else {
System.out.println("The " + getName() + " cant start: " + preconditions
+ " not yet solved.");
}
}
private synchronized void informSolved(final Task task) {
preconditions.remove(task);
start();
}
@Override
public String toString() {
return getName();
}
public static void main(final String[] args) {
Task cup = new Task("Cup");
Task milk = new Task("Milk", cup);
Task coffee = new Task("Coffee", cup);
Task mix = new Task("Mix", milk, coffee);
mix.start();
milk.start();
cup.start();
coffee.start();
}
}
這顯示在控制檯上:
The Mix cant start: [Milk, Coffee] not yet solved.
The Milk cant start: [Cup] not yet solved.
The Coffee cant start: [Cup] not yet solved.
Working Cup
Working Coffee
The Mix cant start: [Milk] not yet solved.
我的問題:我有什麼做的就是我的咖啡混合使用嗎?
當我讀你的標題時,我以爲我很高。 – Maroun
,而任務可能有許多預備,每個初步任務只能有一個任務。但在你的例子中,「杯子」應該有2個任務 - >牛奶和咖啡。所以用「addPostTask」邏輯改變「setPostTask」,你很好。 – frail
@frail多數民衆贊成它!謝謝 –