What is an example of a design pattern?

John Moore

Following the lead of the “Gang of Four” (GoF), design pattern descriptions usually contain multiple sections including

  • Intent
  • Motivation
  • Applicability
  • Structure
  • Participants
  • Collaborations
  • Consequences
  • Implementation
  • Sample Code
  • Known Uses
  • Related Patterns
A complete discussion of even a small pattern is beyond the scope of a simple FAQ entry, but it is possible to get the idea by examining an abbreviated discussion of one of the simplest and most easily understood patterns. Consider the Singleton pattern, whose intent reads as follows:
Intent: Ensure that a class has one instance, and provide a global point of access to it.
Almost every programmer has encountered this problem and formulated an approach for solving it in a general way – some solutions are better than others. The solution offered by the GoF would look something like the following when coded in Java.
public class Singleton
    private static Singleton instance = null;

    public static Singleton getInstance()
        if (instance == null)
            instance = new Singleton();
        return instance;

    protected Singleton()     { ... }
    // possibly another constructor form

    public void someMethod()  { ... }

    //... other methods
The programmer would access the single instance of this class by writing something similar to
or similar to
Singleton s = Singleton.getInstance();
For a more complete discussion of the Singleton pattern, see the chapter “Singleton” in the book Design Patterns: Elements of Reusable Object-Oriented Software by the “Gang of Four” (Addison-Wesley, 1995), or the chapter “Singleton” in the book Patterns in Java, Volume 1 by Mark Grand (John Wiley & Sons, 1998). For information about variations on the Singleton Pattern, see the chapter entitled “To Kill a Singleton” in the book Pattern Hatching: Design Patterns Applied by John Vlissides or the article “Implementing the Singleton Pattern in Java” by Rod Waldhoff.