Tutorial 08: Stacks and Queues

The Adapter Pattern


Introduction

Stacks and queues are examples of containers with special insertion and removal behaviors and a special access behavior.

Insertion and removal in a stack must be carried out in such a way that the last data inserted is the first one to be removed.   One can only retrieve and remove a data element from a stack by way of special access point called the "top".   Traditionally, the insertion and removal methods for a stack are called push and pop, respectively.  push inserts a data element at the top of the stack.  pop removes and returns the data element at the top of the stack.  A stack is used to model systems that exhibit LIFO (Last In First Out) insert/removal behavior.    In the upcoming project, you will be asked to implement a postfix calculator using a stack as its "engine".

Data insertion and removal in a queue must be carried out in such a way that  the first one to be inserted is the first one to be removed.   One can only retrieve and remove a data element from a queue by way of special access point called the "front".  Traditionally, the insertion and removal methods for a queue are called enqueue and dequeue, respectively.  enqueue inserts a data element at the "end" of the queue.  dequeue removes and returns the data element at the front of the queue.  A queue is used to model systems that exhibit FIFO  (First In First Out) insertion/removal behavior.  For example, one can model a movie ticket line by a queue.

Stacks and queues can be easily implemented by composing with one of the linear recursive structures studied so far.  This is called the "adapter pattern".  The adapter pattern is used to make one class look like another class with a different set of public methods.   It comes in two flavors:

This tutorial consists of the simple task of implementing the abstract Stack and Queue structures by adapting the Circular List structures.  The coding should be trivial.


Exercises

  1. Write the code for IStack, IQueue, CListStack, CListQueue as specified in SQDoc.  You will need to write appropriate ICLVisitor to check CLList for emptiness and for fullness.   CLList and ICLVisitor are defined in Circular List.   This is the object adapter pattern.

    Food for thought: Does it make sense to apply the visitor pattern to IStack and IQueue?  If it does, how would you specify  and implement the visitors?  Take your time after the lab to think and come up with an answer.

  2. The object adapter pattern is also used to ensure that only specific types of objects are stored in a particulat container.   The javadoc Type Specific illustrates this application of the adpater pattern.  Write the code for StackInt and QueueString as specified in the UML diagram.

  3. Below is a two-way stack/list adapter using multiple inheritance (Two Way).  Write the code for CListStack2Way.

D. X. Nguyen, Oct. 30, 2000.
dxnguyen@cs.rice.edu