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.
  1. Single thread singleton
class Singleton{
    private Singleton(){};
    private static Singleton singleton;
    public Singleton getInstance(){
        if(singleton==null){
             singleton=new Singleton();
        }
        return singleton;
    }
}
  1. 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;
    }
}
  1. early created one
    public class Singleton{
    private static Singletion uniqueInstance=new Singleton();
        private Singleton(){};
        public Singleton getInstance(){
            return  uniqueInstance;
        }
    }
  1. 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.

你可能感兴趣的:(设计模式,单例模式,Singleton)