Intent: A short statement that answers the following questions: What does the design pattern do? What is its rationale and intent? What particular design issue or problem does it address?
Also Known As: Other well-known names for the pattern, if any.
Motivation : A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. The scenario will help us to understand the more abstract description of the pattern that follows.
Applicability : What are the situations in which the design pattern can be applied? What are examples of poor designs that the pattern can address?
Structure, Participants & Collaborations: A graphical representation of the classes in the pattern. The classes and/or objects participating in the design pattern and their responsibilities. Implementation : What pitfalls, hints, or techniques should we be aware of when implementing the pattern?
Sample Code: Sample code with example program.
We will start the series with the pattern "Singleton".
Intent: Ensure a class only has one instance, and provide a global point of access to it.
Motivation:
It's important for some classes to have exactly one instance. Although there can be many printers in a system, there should be only one printer spooler. There should be only one file system and one window manager. A digital filter will have one A/D converter. An accounting system will be dedicated to serving one company.
How do we ensure that a class has only one instance and that the instance is easily accessible? A global variable makes an object accessible, but it doesn't keep you from instantiating multiple objects.
A better solution is to make the class itself responsible for keeping track of its sole instance. The class can ensure that no other instance can be created (by intercepting requests to create new objects), and it can provide a way to access the instance. This is the Singleton pattern.
Applicability
Use the Singleton pattern when,
- There must be exactly one instance of a class, and it must be accessible to clients from a well-known access point.
- When the sole instance should be extensible by subclassing, and clients should be able to use an extended instance without modifying their code.
Structure, Participants & Collaborations
- Defines an Instance operation that lets clients access its unique instance. Instance is a class operation (that is, a class method in Smalltalk and a static member function in C++).
- May be responsible for creating own unique instance.
A singleton class can't have a public constructor and it has to be sealed. The entry point to get the singleton instance would be a static method or a static property.
Sample Code:
public sealed class ClassTeacher
{
private static ClassTeacher instance = new ClassTeacher();
private ClassTeacher(){ }
public static ClassTeacher Instance
{
get
{
return instance;
}
}
}
No comments:
Post a Comment