Notes on Patterns

Recommended Books

Click to read reviews or buy Click to read reviews or buy

In their seminal work on patterns, Design Patterns, , the Gang of Four group them into three types, Creation, Structural, Behavioral.

  1. Creation Patterns
    1. The Singleton

      This pattern uses a single instance of a class in a system. In Java, a good example of this is the Runtime object. It is never constructed by a user, just the reference is obtained with Runtime.getRuntime().

      I've used the Singleton pattern with a ConnectionPool class. The constructor looks like this:

      public class ConnectionPool {
        private static ConnectionPool connectionPool = null;
      //make it private so no one outside can call it 
      private ConnectionPool(String initFile) throws Exception
      public static ConnectionPool getConnectionPool() throws Exception
          if(connectionPool == null) {
           synchronized (Class.forName("ConnectionPool")) {
              if(connectionPool == null) {
      	   connectionPool = new ConnectionPool("C:/InetPub/conf/site.prop");
          return connectionPool;

      A user of this class would grab a reference to an instance of the class with something like,

      try {
         ConnectionPool myConnectionPool = ConnectionPool.getConnectionPool();
    2. Factory

      This pattern lets a Factory class actually instantiate the correct type of subclass of the object. [Example code goes here]

    3. Null Object

      Instead of littering your code with repeating code like:

      myObject = getObject();
      if(myObject != null) {

      Create a do nothing instance of the object that is returned from "getObject()" that implements all the methods of the object, but does nothing. The code above is replaced with:

      myObject = getObject();

      Or even


      From Kevlin Henney's article in Java Report Dec 1999.

  2. Structural Patterns
    1. Decorator Pattern:

      The decorator pattern adds design flexibility over subclassing by dynamically wrapping objects with similiarly typed objects with the same operations.

      Decorator Pattern Exercise: You have been hired by Microsoft and the RIAA to write the next generation DRM software for the upcoming iZune music player. They don't know exactly what encryption technique will be used in the future but they know they might want to encrypt using DES, pgp, blowfish, and rsa - and they may want to do combinations of the encryptions. Design a class hierarchy.

      Their current software for the unrestricted mp3 player for a song is:

      Class:  Song
      Method:  Play()
  3. Behavioral Patterns
  4. Examples coming...

Good Links for Patterns
  1. Patterns Home Page
  2. Model-View-Controller-Client Framework
Go to Home page. Kindly report errors, typos, or misspellings here.