Exercise: Complex Scenarios
Unqueueing Tails
Easy, right? Now we get to the nasty part: Getting tails back out again!
- If there are any Urgent tails, always send them first. (Don't rotate preference.)
- If there are no other tails available, send a Dismissed tail. (Don't rotate preference.)
- Otherwise, look for tails in your preferred priority, IMPORTANT or REQUESTING. If you have one, return it and rotate the preference.
- If there's nothing in your preferred priority, look in the other priority. (Don't rotate preference.)
- If there are no tails at all, return null. (Don't rotate preference.)
CompareTo()
.
Our programmer used a very simple state machine with just three states:
- STATE_IMPORTANT_FIRST (0) — means we're preferring our first IMPORTANT tail.
- STATE_REQUESTING (1) — means we're preferring a REQUESTING tail.
- STATE_IMPORTANT_SECOND (2) — means we're preferring our second IMPORTANT tail.
public class TailQueue
public Tail Get()
{
if (queues[Tail.URGENT].IsEmpty)
return GetNextInRotation();
return Dequeue(Tail.URGENT);
} private Tail GetNextInRotation()
{
switch(state)
{
case STATE_IMPORTANT_FIRST:
return Get(Tail.IMPORTANT, Tail.REQUESTING, STATE_REQUESTING);
case STATE_REQUESTING:
return Get(Tail.REQUESTING, Tail.IMPORTANT, STATE_IMPORTANT_SECOND);
case STATE_IMPORTANT_SECOND:
default:
return Get(Tail.IMPORTANT, Tail.REQUESTING, STATE_IMPORTANT_FIRST);
}
}
public class TailQueue
{
private Tail Get(int firstChoice, int secondChoice, int nextState)
{
if (!queues[firstChoice].IsEmpty)
{
state = nextState;
return Dequeue(firstChoice);
}
if (!queues[secondChoice].IsEmpty)
return Dequeue(secondChoice); if (!queues[Tail.DISMISSED].IsEmpty)
return Dequeue(Tail.DISMISSED); return null; } private Tail Dequeue(int queueNumber)
{
IEnumerator enumerator = queues[queueNumber].GetEnumerator();
enumerator.MoveNext();
Tail result = (Tail)enumerator.Current;
queues[queueNumber].Remove(result);
return result;
} …
}
(Reading...)
Formatting Hints:
To format... | use this markup: |
---|---|
source code | {source:lang=java|lineNumbers=false}...{source} (Supported languages: java, cpp, csharp, c, python.) |
bold text | __some text__ |
italicized text | ~~some text~~ |
underlined text | @@some text@@ |
a method or class name | ``myMethod(...)`` |