Wednesday, July 28, 2010

Design Patterns-Singleton Pattern

Singleton Pattern


The intent of the Singleton pattern defined in Design Patterns is -
To "ensure a class has only one instance, and provide a global point of access to it".

what problem does this solve,?
what is our motivation to use it?

In nearly every application, there is a need to have an area from which to globally access and maintain some type of data. There are also cases in object-oriented (OO) systems where there should be only one class, or a predefined number of instances of a class, running at any given time. For example, when a class is being used to maintain an incremental counter, the simple counter class needs to keep track of an integer value that is being used in multiple areas of an application. The class needs to be able to increment this counter as well as return the current value. For this situation, the desired class behavior would be to have exactly one instance of a class that maintains the integer and nothing more.

Another simple example is :
You are creating Database connection class.creating its object and sharing in the project.

Logical Model

The model for a singleton is very straightforward. There is (usually) only one singleton instance. Clients access the singleton instance through one well-known access point. The client in this case is an object that needs access to a sole instance of a singleton.

Ee817670.singletondespatt01(en-us,PandP.10).gif


Sample Singleton Usage

sealed class SingletonCounter {
public static readonly SingletonCounter Instance =
new SingletonCounter();
private long Count = 0;
private SingletonCounter() {}
public long NextValue() {
return ++Count;
}
}

class SingletonClient {
[STAThread]
static void Main() {
for (int i=0; i<20;>
----------------------------------------
The Singleton design pattern is a very useful mechanism for providing a
single point of object access in an object-oriented application.
Regardless of the implementation used, the pattern provides a commonly
understood concept that can be easily shared among design and
development teams.


The .NET Framework goes a long way to help an implementer
of a pattern design the type of functionality desired without having to
deal with many of the side effects discussed in this article.

No comments:

Post a Comment