Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
DevExpress UI Controls
Search :       Advanced Search »
Home » Design & Architecture » Singleton Design Pattern in C#

Singleton Design Pattern in C#

Design Patterns provide solutions to common recurring problems. Design patterns can be classified as creational, structural or behavioral .Singleton and Factory patterns are two of the creational pattern.Here we will discuss these two patterns.

Author Rank :
Page Views : 4125
Downloads : 0
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 


HTML clipboard

Design Patterns provide solutions to common recurring problems. Design patterns can be classified as creational, structural or behavioral .Singleton and Factory patterns are two of the creational pattern.Here we will discuss these two patterns .In the later posts we will discuss other design patterns.

Singleton Design Pattern

We use this design pattern when we want to restrict the number of instances of any object to one at max at any instant of time. The practical implementation of this design pattern can be seen in applications that we use daily. Take the example of Microsoft word .What happens when you open multiple word documents and navigate between them?. There is only one instance of the word application active at a time ,you can verify this by checking the active processes .So all the requests for handling the different word documents is handled by a single application instance.

Here is an implementation of the singleton design pattern in C#. We will use a console application for this example. We will create a class and define a private constructor in that class so that the instances of that class can be created from only within that class.

       private Singleton()
        {

        }

Since we declare our class constructor as shown above we can not access it from outside the class .The below statement will give compilation error

     Singleton obj = new Singleton(); 

To access the single object of the Singleton class we will create a static variable of type Singleton and a property to access that private variable.

Here is the complete source code of the above example :

   class Singleton
    {
        private Singleton()
        {

        }
        //private static variable of Singleton type.
        private static Singleton objSingle = new Singleton();

        //declare a public static property that returns the
        //Singleton object as we can not call the private
        //constructor from outside the class.
        public static Singleton ObjSingle
        {
            get { return Singleton.objSingle; }
            set { Singleton.objSingle = value; }
        }

        private string name;

        public string Name
        {
            get { return name; }
            set { name = value; }
        }
 
    }
    class Program
    {

        static void Main(string[] args)
        {
            //the below line create an object of singleton type
            Singleton objFirstObject = Singleton.ObjSingle;
            objFirstObject.Name = "ashish";
            //if we access the objSingle property from another variable we will get the same object
            Singleton objSecondObject = Singleton.ObjSingle;
            //We have assigned the name in first object,we will get the same value in second object since both points
            //to the same instance
            Console.WriteLine("objFirstObject.Name={0} ,objSecondObject.Name={1}",objFirstObject.Name,objSecondObject.Name);
            Console.ReadLine();
        }

    }

Factory Method Pattern

In the Factory method pattern there is Factory method which decides which subclass to instantiate depending on the information passed by the client. All the subclasses implement a common interface.

The client declares a variable of interface type and calls the Factory method that returns an instance of the subclass to the client code.So the client is decoupled from the implementation details of subclass creation.

Following is an example of factory method pattern.

        interface IGreet
        {
            string Hello();
        }
 
        class WeekStart : IGreet
        {
            public string Hello()
            {
                return " Week Started";
            }
        }
 
        class WeekEnd : IGreet
        {
            public string Hello()
            {
                return "Happy Weekend";
            }

        }
        class Creator
        {
            public IGreet FactoryMethod()
            {
                if (DateTime.Now.DayOfWeek == DayOfWeek.Monday || DateTime.Now.DayOfWeek == DayOfWeek.Tuesday
                || DateTime.Now.DayOfWeek == DayOfWeek.Wednesday || DateTime.Now.DayOfWeek == DayOfWeek.Thursday
                )
                    return new WeekStart();
                else
                    return new WeekEnd();
            }
        }

        class Program
        {
            private DateTime dt = DateTime.Now;

            static void Main(string[] args)
            {
                Creator ct = new Creator();
                IGreet weekDayStatus = ct.FactoryMethod();
                Console.WriteLine(weekDayStatus.Hello());
                Console.ReadLine();

            }
        }
 

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 [Top] Rate this article
 
 About the author
 
Ashish Shukla
Having more than 7 years of experience in .NET,C#,Silverlight and SQL Server.Like to read books and travel in spare time.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
Nevron Chart
Become a Sponsor
 Comments
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.