diff src/samer/tools/CompoundTask.java @ 0:bf79fb79ee13

Initial Mercurial check in.
author samer
date Tue, 17 Jan 2012 17:50:20 +0000
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/src/samer/tools/CompoundTask.java	Tue Jan 17 17:50:20 2012 +0000
@@ -0,0 +1,101 @@
+/*
+ *	Copyright (c) 2000, Samer Abdallah, King's College London.
+ *	All rights reserved.
+ *
+ *	This software is provided AS iS and WITHOUT ANY WARRANTY; 
+ *	without even the implied warranty of MERCHANTABILITY or 
+ *	FITNESS FOR A PARTICULAR PURPOSE.
+ */
+
+package samer.tools;
+
+/**
+  *		This is a task that consists of a list of
+  *		sub tasks. The task is no more than the sum
+  *		of its subtasks -- ie there can be no extra
+  *		processing other than that done by the tasks
+  *		in the list. This is why the Task methods
+  *		are decalared <code>final</code>.
+  */
+
+public class CompoundTask implements Task
+{
+	private TaskLink head=null, tail=null;
+
+	public CompoundTask() {}
+	public CompoundTask(Task t) { addTask(t); }
+
+	public String toString() { return "CompoundTask"; }
+	
+	// task list implementation
+
+	public void addTask(Task t)
+	{
+		if (head==null) {
+			head=new TaskLink(t,null);
+			tail=head;
+		} else {
+			tail.next=new TaskLink(t,null);
+			tail=tail.next;
+		}
+	}
+
+	public void addTaskAfter(Task t, Task b)
+	{
+		if (head==null) addTask(t);
+		else if (b==null) head=new TaskLink(t,head);
+		else {
+			TaskLink q=head;
+			while (q!=null && q.task!=b) q=q.next;
+			if (q!=null) q.next=new TaskLink(t,q.next);
+			else addTask(t);
+		}
+	}
+
+	public void removeTask(Task t)
+	{
+		TaskLink prev=null;
+
+		for (TaskLink l=head; l!=null; prev=l, l=l.next) {
+			if (l.task==t) {
+				if (prev!=null) prev.next=l.next;
+				else head=l.next;
+				if (tail==l) tail=prev;
+			}
+		}
+	}
+
+	public Iterator iterator() { return new Iterator(); }
+
+	// Task implementation
+
+	public final void starting() {
+		for (TaskLink l=head; l!=null; l=l.next) l.task.starting();
+	}
+	public final void stopping() {
+		for (TaskLink l=head; l!=null; l=l.next) l.task.stopping();
+	}
+	public final void run() throws Exception {
+		for (TaskLink l=head; l!=null; l=l.next) l.task.run();
+	}
+	public void dispose() {
+		for (TaskLink l=head; l!=null; l=l.next) l.task.dispose();
+	}
+
+	// using a linked list for speed
+	private static class TaskLink {
+		Task		task;
+		TaskLink next;
+
+		TaskLink(Task t, TaskLink n) { task=t; next=n; }
+	}
+
+	// list iterator
+	public class Iterator implements java.util.Iterator {
+		TaskLink	l=head;
+		public final boolean more() { return l!=null; }
+		public final boolean hasNext() { return l!=null; }
+		public final Task		next() { Task t=l.task; l=l.next; return t; }
+		public final void    remove() { l.task=l.next.task; l.next=l.next.next; }
+	}
+}