Property Based Singleton Design pattern in C#

You may get some of the good information about Design patterns with Software design pattern and .NET Design Patterns.

Here just I want to say few tricks about single ton and implementation at runtime.

Familiar and Traditionally,

  1. NormalProgram objProgram = NormalProgram.Singleton();  
  2. NormalProgram objProgram2 = NormalProgram.Singleton();  
  3.   
  4. if(objProgram == objProgram2)  
  5. {  
  6.    Console.WriteLine("Instances matched");  
  7. }  
Why we are not calling properties for method callings. How to design properties ?

calling properties

Simple we can call and implement and change patterns modeling but intention is to be making ‘Instance must be same’.

We can change Pattern style not behavior

The following code snippets talk about properties in the class. I will demonstrate by using Lazy Keyword.

change Pattern style

  1. public class DemoProgram  
  2. {  
  3.     public static readonly Lazy < DemoProgram > Demo = new Lazy < DemoProgram > (() => new DemoProgram());  
  4.     public static DemoProgram _instance  
  5.     {  
  6.         get  
  7.         {  
  8.             return Demo.Value;  
  9.         }  
  10.     }  
  11.     public DemoProgram()  
  12.     {  
  13.         Console.WriteLine("Lazy Singleton acheived");  
  14.     }  
  15.     public static void TestMethod()  
  16.     {  
  17.         Console.WriteLine("Sample Method call from Singleton Class");  
  18.     }  
  19.     public static DemoProgram SngltonMethod()  
  20.     {  
  21.         return _instance;  
  22.     }  
  23. }  
What new approach says is:

code

In new approach no bother about conditions and checking’s. But it is little lazy than traditional

Ebook Download
View all
Learn
View all