Singleton : Singleton Pattern « Design Patterns « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Date Time
8.Design Patterns
9.Development Class
10.Event
11.File Stream
12.Generics
13.GUI Windows Form
14.Internationalization I18N
15.Language Basics
16.LINQ
17.Network
18.Office
19.Reflection
20.Regular Expressions
21.Security
22.Services Event
23.Thread
24.Web Services
25.Windows
26.Windows Presentation Foundation
27.XML
28.XML LINQ
C# Book
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Design Patterns » Singleton PatternScreenshots 
Singleton
        

using System;
using System.Reflection;


namespace tera.commons.utils
{
    public static class Singleton<T> where T : class
    {
        /// <summary>
        /// The singleton instance itself
        /// </summary>
        private static volatile T m_Instance;
        /// <summary>
        /// The object used to lock the entire singleton repository.
        /// </summary>
        private static object m_Lock = new object();

        /// <summary>
        /// Get the singleton instance of type <see cref="T"/>.
        /// </summary>
        public static T Instance
        {
            get
            {
                // Only create a new instance if there is no instance yet
                // Lock the entire singleton repository and check again for any racing conditions
                if (m_Instance == null)
                    lock (m_Lock)
                        if (m_Instance == null)
                        {
                            // Try to get the private/protected constructor from type T
                            ConstructorInfo constructorInfo;
                            try constructorInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0]null)}
                            //  Could not get the  private/protected constructor
                            catch (Exception exception) { throw new Exception("DefaultMessage", exception)}

                            // Make sure we have a private/protected constructor and not an internal one
                            if (constructorInfo == null || constructorInfo.IsAssembly)
                                throw new Exception("DefaultMessage");

                            // Create a new instance by invoking the constructor
                            m_Instance = (T)constructorInfo.Invoke(null);
                        }

                // The earlier created instance
                return m_Instance;
            }
        }
    }
}

   
    
    
    
    
    
    
    
  
Related examples in the same category
1.Singleton Pattern Demo
java2s.com  |  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.