Standard Design Patterns
Suitable For Use in the
Early Curriculum
Joseph Bergin
There are a number of design patterns from GOF and elsewhere that can be rather easily incorporated into the first two courses in Computer Science. I would like to mention a few of theses and illustrate how they might be used. Mostly these are patterns requiring only one or two classes, or they are coding patterns, independent of class structure. Most of these are discussed in Patterns in Java, by Grand (Wiley, 1998)
Singleton Object [GOF]
Any large object in an application
public class Scanner
{ private Scanner( ){ }
public static Scanner uniqueScanner = new Scanner( );
}
Immutable Object [Grand]
Transaction objects in a simple financial system
A lisp like linked list.
public class List
{ private List cons(Object o){ }
public Object car(){ }
public List cdr() { }
public static List NULL = new List();
}
Adapter [GOF]
Turn a list or Vector into a stack.
Public class Stack
{ private Vector storage = new Vector;
...
public void push(Object o){ }
}
Null Object [Woolf]
End of a list, leaves of trees
public abstract List
{ ...
}
public class NonEmptyList extends List
{ ...
}
public class EmptyList extends List
{ ...
}
Factory method [GOF]
Producing an Enumeration
public class List
{ ...
public Enumeration elements(){ }
private class ListEnumeration implements Enumeration
{ public boolean hasMoreElements() { }
public Object nextElement(){ }
...
}
}
Iterator [GOF]
Enumerations (see above)
Delegation [Grand]
Person with many roles (see Grand)
public class Person
{ ...
}
class Pilot
{ private Person who ...
}
class Passenger
{ private Person who ...
}
Whole-Part [POSA]
Engine, tires on a car
Object Pool [Grand]
Players in a game in which the people can change, but there are a fixed number of "players." File handles, Threads
Observer [GOF]
The easiest is the Java Events Model.
Visitor [GOF]
Tree walks (even List walks).
interface class ListVisitor
{ public Object do (Object o)
}
public class List
{ public Object apply(ListVisitor v){ }
}
Function Object (~Command [GOF])
See the visitor above
Note that all of these concern material that most would introduce in any case in the first two courses. The suggestion here is to introduce them as patterns using the techniques in the "Pattern for Teaching Patterns" paper.
Somewhat more elaborate examples that might be introduced with some effort, or simply as examples.
Composite [GOF]
Structure of a word processor or other document handling program.
Filter [POSA]
The Java I/O libraries use this structure
MVC [POSA]
The Java Swing classes are built on this idea
And if threads are taught (as they perhaps should be):
Single Threaded Execution [Grand]
Producer-Consumer [Grand]