C# Tutorials and offshore development in India
    Tutorials   Resources   Forum   Reviews   Communities   Interview   Jobs   Projects   Training   Your Ad Here    
Silverlight Games | Mentor | Code Converter | Articles | Code Factory | Computer Jokes | Members | Peer Appraisal | IT Companies | Bookmarks | Polls | Revenue Sharing | Lobby | Gift Shop |


Prizes & Awards
My Profile



Active Members
TodayLast 7 Days more...






Resources » Articles » .NET Framework »

Singleton Class.


Posted Date: 28 Sep 2004    Resource Type: Articles    Category: .NET Framework
Author: N.ManikandanMember Level: Silver    
Rating: 1 out of 5Points: 5



There may be many situations where u may need to create only one instance of a class. This concept is called as Singleton Class.

Singleton Class is one of the main concepts in Design Patterns and it is most frequently used.

This example will explain you to create a singleton class.



class Singleton
{
private static Singleton sin=null;
private static bool flag;
private Singleton()
{
}
public static Singleton Create()
{
if(!flag)
{
sin=new Singleton();
flag=true;
return sin;
}
else
{
return sin;
}
}
protected void Finalize()
{
flag=false;
}
}

class Class1
{
/// The main entry point for the application.
static void Main(string[] args)
{
//creating the object
Singleton sin1,sin2;
sin1=Singleton.Create();
if(sin1!=null)
{
Console.WriteLine("Yes Object Created...");
}
sin2=Singleton.Create();
if(sin2!=null)
{
Console.WriteLine("Yes Object Created...");
}
else
{
Console.WriteLine("Object not Created...");
}

Console.Read();

}
}


Hope this will help u out

from Mani
9886560200.



Responses

Author: Noshirwan Sheriyarji    02 Jan 2005Member Level: Bronze   Points : 0
Please publish more such on the other different patterns too but more importantly keep it as simple as this.
Thanks,
Nosh


Author: Murray E. Watt    04 Jan 2005Member Level: Bronze   Points : 0
A CSharp Singleton Class

Summary

The current singleton sample posted to this form is not as clean as it could be and has a bug. This article presents a cleaner implementation of the singleton pattern and addresses the finalization problem.

Introduction

The singleton pattern is used when you want to have exactly one instance of an object, such a print spooler or a logging facility. It is a clean way of sharing global data such as application settings in an object oriented fashion.

A singleton requires three parts:

• A member to store a reference to the single instance of the object
• A private version of the constructor, so that it cannot be created more than once (by making sure the object can only create itself).
• A static member by which other objects can get a reference to the singleton

The following in the minimum implementation of the singleton class:

class Singleton
{
// Singletons have a static member
//that points to the one instance

private static Singleton _instance;

// Singletons have a private constructor
// This makes sure that the single instance
// is only created from with in the Instance accessor.

private Singleton() {}

// The Instance propety will create
// the Singleton if it does not exist

internal static Singleton Instance
{
get
{
if (_instance == null)
{
_instance = new Singleton();
}

return _instance;
}
}
}

Since this implementation of a singleton has a referrence to itself, its memeory will not be released until the application ends or the appDomain where the singleton lives is released. If you want to release the memory earlier, we can add a method to null out the sigletons reference to itself. This introduces a potential for bugs which we address later in this article.

To enble the memory to be released earily we can add the following method.

internal static void Release()
{
_instance = null;
}

“Releasing” the singleton does not stop any objects that still retain references to the singleton from continuing to use it. Also there isn’t anything keeping the application from recreating the singleton. There is a benefit to the second point. The application to reduce the memory load when the singleton is not needed; however, when combined with the first point you can end up with two active copies of the singleton.

The solution is to add a flag that lets one know if the instance has been released.

private static bool _isReleased;

The Release method becomes

internal static void Release()
{
_instance = null;
_isReleased = true;
}

Then we add the following validation to the properties and methods

if (_isReleased == true)
{
throw(new Exception("message"));
}

The new version of the singleton now looks like this:

#region Using directives

using System;

#endregion

namespace Singleton_Project
{
class Singleton
{
// Singletons have a static member
// that points to the one instance

private static Singleton _instance; // auto-initialized to null
private static bool _isReleased; // auto-initialized to false

// Singletons have a private constructor
// This makes sure that the single instance
// is only created from with in the Instance accessor.

private Singleton()
{
}

// The Instance propety will create
// the Singleton if it does not exist

internal static Singleton Instance
{
get
{
if (_isReleased == true)
{
throw(new Exception("An attempt has ..."));
}

if (_instance == null)
{
_instance = new Singleton();
}

return _instance;
}
}

internal static void Release()
{
if (_isReleased == true)
{
throw(new Exception("An attempt has ..."));
}

_instance = null;
_isReleased = true;
}
}

class Program
{
static void Main(string[] args)
{
Singleton reference1ToSingleton = Singleton.Instance;
Singleton reference2ToSingleton = Singleton.Instance;

if (reference1ToSingleton == null)
{
Console.WriteLine("Object not created");
}
else
{
Console.WriteLine("Object created");
}

if (reference1ToSingleton.Equals(reference2ToSingleton)
{
Console.WriteLine("Both references are to the same object.");
}
else
{
Console.WriteLine("The two references are to differenct objects.");
}
}
}
}

The output of this program is:

Object created
Both references are to the same object.



Author: Murali Krishna Kunapareddy    20 Sep 2005Member Level: Bronze   Points : 0
This sample could be simpler and there is a bug by Murray E. Watt is really great and helped me a lot. In fact, this is betterthan the main.

Thanks once again

Murali Krishna


Author: Nanda    17 Jan 2006Member Level: Bronze   Points : 0
Murrya, awesome sample. Thought we can make it thread safe

internal static Singleton Instance
{
get
{
if (_instance == null)
{ {
lock(_instance)
{

_instance = new Singleton();
}
}
return _instance;
}
}

Nice posting in http://www.yoda.arachsys.com/csharp/singleton.html


Feedbacks      
Popular Tags   What are tags ?   Search Tags  
Sign In to add tags.
(No tags found.)

Post Feedback


This is a strictly moderated forum. Only approved messages will appear in the site. Please use 'Spell Check' in Google toolbar before you submit.
You must Sign In to post a response.
Next Resource: “Basics Windows Forms-Questions and Answer for DotNet People”
Previous Resource: Difference b/w 'Dim obj as Emp' and Dim obj as New Emp
Return to Discussion Resource Index
Post New Resource
Category: .NET Framework


Post resources and earn money!
 
More Resources



dotNet Slackers

About Us    Contact Us    Privacy Policy    Terms Of Use