Singleton Pattern ——book review by Mac

Ways of singleton pattern can manage the situation where a object can only be created once .They need to trade off to satisfy different ones.
  • Single thread singleton
  • class Singleton{
        private Singleton(){};
        private static Singleton singleton;
        public Singleton getInstance(){
            if(singleton==null){
                 singleton=new Singleton();
            }
            return singleton;
        }
    }
  • Multi-thread ones the less efficient one for multi-thread and lazy created
  •  class Singleton{
        private Singleton(){};
        private static Singleton singleton;
        public  synchronized Singleton getInstance(){
            if(singleton==null){
                 singleton=new Singleton();
            }
            return singleton;
        }
    }
  • early created one
  •     public class Singleton{
        private static Singletion uniqueInstance=new Singleton();
            private Singleton(){};
            public Singleton getInstance(){
                return  uniqueInstance;
            }
        }
  • double check one (2)More efficient one
  • public class Singleton{
        private volatile static Singleton uniqueInstance;
        private Singleton(){};
        public static Singleton getInstance(){
            if(uniqueInstance==null){
                synchronized(Singleton.class){
                    if(uniqueInstance==null){
                        uniqueInstance=new Singleton();
                    }
                }
            }
        }
    }

    Principles 1. synchronized ones costs lots of overhead. 2. double check can not be used in the JVM version of 1.4 or before. 3. In JVM 1.2 or earlier ones the singleton object would be collected by garbage collect system when no reference out of the object points to the object. 4. synchronized method may not be used if not that necessary.

    좋은 웹페이지 즐겨찾기