Java设计模式- Singleton

作者: 何恩 | 来源:发表于2014-06-15 20:37 被阅读6833次

    Java 设计模式 单例模式 Singleton


    1.懒汉(线程安全)

    //懒汉
    public class Singleton {
        private static Singleton singleton;
    
        private Singleton() {
    
        }
    
        public static synchronized Singleton getSingleton() {
            if (singleton == null) {
                singleton = new Singleton();
            }
    
            return singleton;
        }
    }
    

    2.饿汉

    //饿汉
    public class Singleton {
        private static final Singleton singleton = new Singleton();
    
        private Singleton () {
    
        }
    
        public static Singleton getSingleton() {
            return singleton;
        }
    }
    

    3.静态内部类

    //静态内部类
    public class Singleton {
        private static class SingletonHolder {
            private static final Singleton singleton = new Singleton();
        }
    
        private Singleton() {
    
        }
    
        public static Singleton getSingleton() {
    
            return SingletonHolder.singleton;
        }
    }
    

    4.枚举

    //枚举
    public enum Singleton {
        INSTANCE;
    
        public void whateverMethod() {
    
        }
    }
    

    5.double-lock

    //double-lock
    public class Singleton {
        private volatile static Singleton singleton;
    
        private Singleton() {
    
        }
    
        public static Singleton getSingleton() {
            if (singleton == null) {
                synchronized(Singleton.class) {
                    if (singleton == null) {
                        singleton = new Singleton();
                    }
                }
            }
    
            return singleton;
        }
    }
    

    相关文章

      网友评论

        本文标题:Java设计模式- Singleton

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