Home | Articles|Namespace|Interview Questions|Tools|Jobs|Projects|Community
Asp.net Tutorials

»Dotnet Ads
»Message Boards
Message Boards
Dotnet Books

»Member Details
Register
Login
LogOut
Submit Code
Submit Jobs
Submit Projects

»Competition
Community
Winners
Prizes
Write For Us
Members

»Other Resources
Links
Dotnet Resources

Singleton Patterns in C#

The software design patterns are mainly classified into three categories, namely Creational Patterns, Structural Patterns and Behavioral Patterns. The Creational Patterns deals with the best way to create objects. The Singleton Pattern is an example of Creational Pattern.

The singleton design pattern is used when only one instance of an object is needed throughout the lifetime of an application. The singleton class is instantiated at the time of first access and the same instance is used thereafter till the application quits.

The famous GOF defined the Singleton Pattern as follows.

“Ensure a class has only one instance, and provide a global point of access to it.” -- "Design Patterns” Gamma et al., Addison-Wesley, ISBN:0-201-63361-2”

The Singleton class can be used in various places where one would need
a common repository of information that can be accessed from all objects in an application. For example sometimes we may need a single Database connection object or Network connection object.

Non-software Example

The office of the President of the United States is a Singleton. The United States Constitution specifies the means by which a president is elected, limits the term of office, and defines the order of succession. As a result, there can be at most one active president at any given time. Regardless of the personal identity of the active president, the title, "The President of the United States" is a global point of access that identifies the person in the office. [Michael Duell, "Non-software examples of software design patterns", Object Magazine, Jul 97, p54]

It is pretty easy to implement the Singleton Pattern in C#. There are lots trivial ways to achieve this. But by using a private constructor and a static method to create an instance of the class is a popular way to create singleton pattern.

The above program will display OK and then followed by NO MORE OBJECTS. The value of the object sic2 is null, because we can’t

Have a Question and dont know the answer post it below and get answers in minutes

Due to spam this feature is disabled
To get answers fast , make sure you enter a detailed subject for example: "DataGrid issues need answer" not "DataGrid"

Subject:

Catjegory Name:

Message:



© 2008 dotnetwatch.com -- Privacy policy