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, throw
TailNotFoundException
. (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.
Tail TailQueue::get()
{
if (m_queues[Tail::URGENT].empty())
return getNextInRotation();
return dequeue(Tail::URGENT);
}Tail TailQueue::getNextInRotation()
{
switch (m_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);
}
}
Tail TailQueue::get(int firstChoice, int secondChoice, int nextState)
{
if (!m_queues[firstChoice].empty())
{
m_state = nextState;
return dequeue(firstChoice);
}
if (!m_queues[secondChoice].empty())
return dequeue(secondChoice);
if (!m_queues[Tail::DISMISSED].empty())
return dequeue(Tail::DISMISSED); throw TailNotFoundException();
}Tail TailQueue::dequeue(int queueNumber)
{
TailSet::iterator first = m_queues[queueNumber].begin();
Tail result = *first;
m_queues[queueNumber].erase(first);
return result;
}class TailNotFoundException : public std::exception
{
public:
TailNotFoundException() { } ~TailNotFoundException() throw() { } const char* what() const throw()
{
return "Not in the queue";
}
};
(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(...)`` |