What is an example of a design pattern?
Created Dec 23, 1999
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
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
Singleton.getInstance().someMethod()or similar to
Singleton s = Singleton.getInstance(); s.method1(); ... s.method2(); ...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.