Guys let’s learn Singleton design
pattern today. By seeing the name you probably guess that it’s something
related to single object ,right ? If you guess so ,then you are master of
design pattern , Just kidding J. Ok, I know you are
learning design pattern and one day you will be among the best.
So come to our discussion again.
Singleton design pattern is one of very essential design pattern in
programmer’s life. Are you thinking ! where it’s needed ? . If you still did
not found any example let me give one.
In website you might aware of hit count
feature. So whenever any user visit the website the hit count variable increase
by one. It’s one wonderful example of singleton patern.
So what happens exactly ? In whole
project only single object of this class (Yes only single object) get create
and all user use it. So the object is global to all user ,It’s not someone’s property.
Lit’s have a look of below code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
namespace BlogProject
{
//Singletone Design patern in C#
public class SingleTone
{
private SingleTone()
{
}
private static SingleTone Single;
public Int32
Pagecount{get;set;}
public static SingleTone ReturnObject()
{
if (Single != null)
{
return Single;
}
else
{
Single = new SingleTone();
return Single;
}
}
}
class Program
{
static void Main(string[] args)
{
SingleTone s = SingleTone.ReturnObject();
s.Pagecount = 100;
SingleTone s1 = SingleTone.ReturnObject();
s1.Pagecount = 200;
Console.WriteLine(s.Pagecount);
Console.ReadLine();
}
}
}
No comments:
Post a Comment