7 Comments


  1. Anirudh

    Can you give some more examples of where Singleton classes are used ? like in any Business logic examples ?

    Reply

  2. Double-checked locking is known to be broken:
    http://www.cs.umd.edu/~pugh/java/memoryModel/DoubleCheckedLocking.html

    Using enums protects against deserialization and reflection, hence enum based singletons are considered the best practics (AFAIK).

    Reply
  3. Karl

    package com.journaldev.singleton;
    public class BillPughSingleton {
    private BillPughSingleton(){}

    private static class SingletonHelper{
    private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }

    public static BillPughSingleton getInstance(){
    return SingletonHelper.INSTANCE;
    }
    }

    Reply
  4. JF

    I tried to do the same in C#. I left out deserialization. Here is the result:

    public class Singleton
    {
        private static Singleton instance;
        public static Singleton GetInstance()
        {
            lock (typeof(Singleton))
            {
                if (instance == null)
                {
                    instance = new Singleton();
                }
            }
            return instance;
        }
        private Singleton()
        {
            if (instance != null)
            {
                throw new Exception("Cannot create singleton instance through reflection");
            }
        }
        protected object MemberwiseClone()
        {
            throw new Exception("Cloning a singleton object is not allowed");
        }
    }
    

    Reply

Leave a Reply.. code can be added in <code> </code> tags