What are the real world applications of the singleton pattern?

后端 未结 10 537
南旧
南旧 2021-02-01 07:22

Duplicate

On design patterns: When should I use the singleton?

class Singleton
{
    private static Singleton instance;

    private Singleton() {}

             


        
相关标签:
10条回答
  • 2021-02-01 08:07

    Assuming your question is in the title:

    I once worked with a COM object that could only have one instance per server. We exposed it to the entire ASP.NET application through a singleton.

    0 讨论(0)
  • 2021-02-01 08:10

    This is not a singleton as a singleton provides the thread safety with readonly keywords.

    For example,

    public sealed class Singleton
    {
        // private static Singleton instance; (instead of this, it should be like this, see below)
        private static readonly Singleton instance = new Singleton();
    
        static Singleton(){}
    
        private Singleton() {}
    
        public static Singleton Instance
        {
            get
            {
                if (instance == null)
                    instance = new Singleton();
                return instance;
            }
        }
    }
    

    By using this it will provide the tread safety and proper singleton pattern (that is how it is different from a static class). Your code for the singleton were not thread safe.

    For more about singleton, check these links:

    • http://csharpindepth.com/articles/general/singleton.aspx
    • http://aspalliance.com/70_Session_Based_Singleton_Object
    0 讨论(0)
  • 2021-02-01 08:12

    In my project we created a logger component which is getting used for logging in the application to different sources (e.g. text file, XML, and database, based on configurations). So there is a log manager which creates the only one instance of the logger class across the application for logging the message, errors, etc.

    0 讨论(0)
  • 2021-02-01 08:12

    You should use a Singleton when there should only be one instance of an object. However, Misko Hevery has some thoughts on why Singletons are bad!

    0 讨论(0)
提交回复
热议问题