1. Advertising
    y u no do it?

    Advertising (learn more)

    Advertise virtually anything here, with CPM banner ads, CPM email ads and CPC contextual links. You can target relevant areas of the site and show ads based on geographical location of the user if you wish.

    Starts at just $1 per CPM or $0.10 per CPC.

C# Design Patterns : Singleton

Discussion in 'C#' started by sigmainfo, Mar 27, 2013.

  1. #1
    Today, I'm sharing that might benefits you.

    Design patterns are recurring solutions to software design problems we find again and again in real-world object oriented application development. Design patterns are there to address a variety of design problems, from small issues to large, architecture-level problems. Here, I am starting a thread which explains different categories of design patterns and their usage. Design patterns are not language specific. Here I have tried to use C# to demonstrate design patterns examples. Design patterns are categorized in three groups: Creational, Structural, and Behavioral. I will be using following format to explain design pattern to make it consistent across all patterns. Name and Category: Describes the name of the pattern and category of pattern (Creational, Structural, or) Behavioral). Intent: It describes what kind of design problem this pattern addresses. Motivation: A scenario that illustrates a design problem and how the class and object structures in the pattern solve the problem. Consequences: It will describe the trade-offs of design pattern.

    Here, we will have a look at Singleton design pattern. Name and Category: Singleton (Creational Pattern)
    Intent: Ensure a class only has one instance, and provide a global point of access to it.
    Motivation: Sometimes we want just a single instance of a class to exist in the system For example;
    we want just one window manager. Or just one factory for afamily of products. Let us look into implementation.
    How can I make only one instance of my class?

    First, we will create a private constructor of our class. When constructor is a private then object of that class can not be created at all.

    Here, we are restricting user from creating an instance of a class. But as per our requirement we need to have one and only one constructor. In order to achieve that, we will create a one static method which in turn returns an object of class. Here, is how it goes:

    // Class : Singleton.cs
    using System;
    using System.Collections.Generic;
    using System.Text;
    namespace DesignPattern
    {
    class Singleton
    {
    private static Singleton singleton = null;
    /*** Returns a reference to the single instance.
    * Creates the instance if it does not yet exist.
    * (This is called lazy instantiation.) */
    public static Singleton Instance()
    {
    if (null == singleton)
    singleton = new Singleton();
    return singleton;
    }
    /** The Singleton Constructor.
    * Note that it is private!
    * No client can instantiate a Singleton object! */
    private Singleton() { }
    }
    }
    Code (markup):
    Here, we have a static method Instance() which takes care of single instance.
    In this method first we check whether the static private variable singleton is created or not.
    If it is null it will create a constructor.
    If it is not null it will return the existing one.
    So we are sure that only one instance of our class will be created.
    Now let us think in different way.
    If two threads are trying to access the Instance () method at the same time what will happen? In that case we will be having two instance of our class. It means our class is not a singleton. right?? So, how can we achieve singleton object?

    // Class : Singleton.cs
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Threading;
    namespace DesignPattern
    {
    class Singleton
    {
    private static Singleton singleton = null;
    // Lock synchronization object
    private static object syncLock = new object();
    /*** Returns a reference to the single instance.
    ** Creates the instance if it does not yet exist.
    * (This is called lazy instantiation.) */
    public static Singleton Instance()
    {
    /* Support multithreaded applications through
    * 'Double checked locking' pattern which (once
    * the instance exists) avoids locking each
    * time the method is invoked*/
    if (null == singleton)
    {
    lock (syncLock)
    {
    if (singleton == null)
    {
    singleton = new Singleton();
    }
    }
    }
    return singleton;
    }
    /** The Singleton Constructor.
    * Note that it is private!
    * No client can instantiate a Singleton object! */
    private Singleton()
    {}
    }
    }
    Code (markup):
    This will make sure that only single instance of class will be created. Consequences:
    Benefits: 1) Controlled access to sole instance.

    Hope you liked it.
     
    sigmainfo, Mar 27, 2013 IP
    Le Dangles and charmtolucky like this.
  2. satish68

    satish68 Greenhorn

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #2
    yes it is better to use singleton pattern then using global variables. nice that you have shared info and code for c# users.
     
    satish68, Apr 6, 2013 IP
  3. sigmainfo

    sigmainfo Active Member

    Messages:
    495
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    55
    #3
    Thanks Satish, you find it useful. You can find more related information on blog.

     
    sigmainfo, Apr 7, 2013 IP
  4. Irfi0009

    Irfi0009 Banned

    Messages:
    17,584
    Likes Received:
    33
    Best Answers:
    1
    Trophy Points:
    48
    #4
    relay its amazing and i cheeked your blog
     
    Irfi0009, Apr 9, 2013 IP
  5. sigmainfo

    sigmainfo Active Member

    Messages:
    495
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    55
    #5
    Thanks ethan for finding the blog fruitful. Hope you will like the coming posts as well.

     
    sigmainfo, Apr 9, 2013 IP
  6. satish68

    satish68 Greenhorn

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #6
    softech02 currently i don't have gtalk but sooner i will get. sigmainfo i didn't get the blog name you mentioned in the reply.
     
    satish68, Apr 10, 2013 IP
  7. sigmainfo

    sigmainfo Active Member

    Messages:
    495
    Likes Received:
    6
    Best Answers:
    0
    Trophy Points:
    55
    #7
    Hey satish68, you can find blog at sigma-infosolutions.blogspot.in

     
    sigmainfo, Apr 10, 2013 IP
  8. Juliano Teixeira

    Juliano Teixeira Greenhorn

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    21
    #8
    Here is a useful class that I use for singletons. If you want your class to be a singleton all you have to do is inherit from Singleton<T> where T is your class and make sure there is a private or protected constructor.
    Example:
    public class MyClass : Singleton<MyClass>
    {
        private MyClass() { }
    }
    Code (markup):
    Singleton Abstract Class:
    using System;
    using System.Reflection;
     
    public abstract class Singleton<T> where T : class
    {
        private static volatile T _instance;
        private static object _lock = new object();
     
        protected Singleton()
        {
            ConstructorInfo[] constructorPublic = typeof(T).GetConstructors(BindingFlags.Public | BindingFlags.Instance);
            if (constructorPublic.Length > 0)
            {
                throw new Exception(String.Format("{0} has one or more public constructors so the property cannot be enforced.",
                                                  typeof(T).FullName));
            }
        }
     
        public static T Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_lock)
                    {
                        if (_instance == null)
                        {
                            ConstructorInfo constructorNonPublic = null;
     
                            try
                            {
                                constructorNonPublic = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], null);
                            }
                            catch (Exception e)
                            {
                                throw e;
                            }
     
                            if (constructorNonPublic == null || constructorNonPublic.IsAssembly)
                                throw new Exception(String.Format("A private or protected constructor is missing for {0}", typeof(T).Name));
     
                            _instance = constructorNonPublic.Invoke(null) as T;
                        }
                    }
                }
     
                return _instance;
            }
        }
    }
    Code (markup):
    Juliano Teixeira
    CEO
    http://www.hosting-site.com
     
    Juliano Teixeira, Apr 17, 2013 IP
  9. satish68

    satish68 Greenhorn

    Messages:
    31
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    6
    #9
    thanks a ton Juliano. here you are using generics in C# for creating a singleton pattern. do share if you have more info on patterns, C# and related such as web, open source etc.
     
    Last edited: Apr 25, 2013
    satish68, Apr 25, 2013 IP
  10. wren11

    wren11 Active Member

    Messages:
    89
    Likes Received:
    10
    Best Answers:
    3
    Trophy Points:
    53
    #10
    hey Juliano, nice code, but why catch an exception if your gonna throw it? seems like a redundant line, you should add a finally and handle the exception or rather remove thee seh all together since it will do the same thing
     
    wren11, Apr 27, 2013 IP
  11. wren11

    wren11 Active Member

    Messages:
    89
    Likes Received:
    10
    Best Answers:
    3
    Trophy Points:
    53
    #11
    http://java2s.com/Code/CSharp/Design-Patterns/CatalogDesign-Patterns.htm

    for some more info about design patterns
     
    wren11, Apr 27, 2013 IP