Click here to Skip to main content
15,995,388 members
Please Sign up or sign in to vote.
2.00/5 (4 votes)
See more:
how and in which situation we can use Singletone design pattern?
what is the advantages of Singletone design pattern?
Posted
Updated 3-Jul-13 18:44pm
v2

To implement singletone pattern thread safe is a very important. To its implementation, It should be makesure that my singletone class is thread safe. You can achieve that using readonly modifier.

C#
public class MySingleToneClass
{
   private static readonly MySingleToneClass _instance = new MySingleToneClass();

   private MySingleToneClass(){}

   public static MySingleToneClass GetInstance()
   {
      return _instance;
   }
}

One important note regarding SingleTone pattern that is many experts are aggreed that SingleTone is anti-pattern. The reason behind that SingleTone class is not properly unit-testable and also they discourage global object. Like global data, global object create many problems.
 
Share this answer
 
 
Share this answer
 
v3
Comments
Tanumay99 4-Jul-13 2:00am    
thanks
Purpose :
Singletone is generally use for object optimization purpose. A project to develop a software where number of object is an important issue and the software weight is an important issue we use Single tone.
How :
Step 1: Create a class
Example:
class SingletoneExample
{
}

Step 2: Set the constructor as private.
Example:
class SingletoneExample
{
   private SingletoneExample()
  {
  }
}

Step 3: Create class type reference variable.
Example :
C#
class SingletoneExample
{
   private SingletoneExample instance;
   private SingletoneExample()
  {
  }
}


Step 4: Create a method. Set the method type as Class Type.create a object with the reference of class type varible and return it.
class SingletoneExample
{
   private SingletoneExample instance;
   private SingletoneExample()
  {
  }
  public static SingletoneExample getInstance()
  {
    instance=new SingletoneExample();
    return instance;
  }
}

Step 5: From other class you call the singletoneExample class behaviour.
Step 6: The singletoneExample class becomes singletone.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900