美文网首页
单例模式

单例模式

作者: Hong2018 | 来源:发表于2017-04-19 14:46 被阅读0次

    单例<件>模式

    1.急切实例化 <饿汉>

    public class Singleton {
        
        private static Singleton uniqueInstance = new Singleton();
    
        private Singleton() {}
    
        public static Singleton getInstance() {
            
            return uniqueInstance;
        }
    }
    

    2.同步getInstance()方法

    public class Singleton{
        
        private SingleTone() {}
        
        public static synchronized Singleton getInstance() {
            
            if (uniqueInstance == null) {
                
                uniqueInstance = new Singleton();
            }
    
            return uniqueInstance;
        }
    }
    

    3.双重检查枷锁 <性能比同步getInstance()好, 需要JDK Java5或以上>

    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();
                    }
                }
    
            }
        }
    }
    

    相关文章

      网友评论

          本文标题:单例模式

          本文链接:https://www.haomeiwen.com/subject/oaxhzttx.html