美文网首页
单例模式

单例模式

作者: hTangle | 来源:发表于2019-04-07 21:38 被阅读0次

    饿汉模式

    public class Singleton1 {
        // 私有构造
        private Singleton1() {}
    
        private static Singleton1 single = new Singleton1();
    
        // 静态工厂方法
        public static Singleton1 getInstance() {
            return single;
        }
    }
    

    懒汉模式

    // 懒汉式单例
    public class Singleton2 {
    
        // 私有构造
        private Singleton2() {}
    
        private static Singleton2 single = null;
    
        public static Singleton2 getInstance() {
            if(single == null){
                single = new Singleton2();
            }
            return single;
        }
    }
    

    线程安全懒汉模式

    public class Singleton4 {
        // 私有构造
        private Singleton4() {}
    
        private static Singleton4 single = null;
    
        // 双重检查
        public static Singleton4 getInstance() {
            if (single == null) {
                synchronized (Singleton4.class) {
                    if (single == null) {
                        single = new Singleton4();
                    }
                }
            }
            return single;
        }
    }
    

    静态内部类,序列化对象,默认方式是多例的

    package org.mlinge.s06;
     
    public class MySingleton {
        
        //内部类
        private static class MySingletonHandler{
            private static MySingleton instance = new MySingleton();
        } 
        
        private MySingleton(){}
         
        public static MySingleton getInstance() { 
            return MySingletonHandler.instance;
        }
    }
    

    支持序列化

    import java.io.ObjectStreamException;
    import java.io.Serializable;
     
    public class MySingleton implements Serializable {
         
        private static final long serialVersionUID = 1L;
     
        //内部类
        private static class MySingletonHandler{
            private static MySingleton instance = new MySingleton();
        } 
        
        private MySingleton(){}
         
        public static MySingleton getInstance() { 
            return MySingletonHandler.instance;
        }
        
        //该方法在反序列化时会被调用,该方法不是接口定义的方法,有点儿约定俗成的感觉
        protected Object readResolve() throws ObjectStreamException {
            System.out.println("调用了readResolve方法!");
            return MySingletonHandler.instance; 
        }
    }
     
    

    静态代码块

    public class MySingleton{
         
        private static MySingleton instance = null;
         
        private MySingleton(){}
     
        static{
            instance = new MySingleton();
        }
        
        public static MySingleton getInstance() { 
            return instance;
        } 
    }
    

    参考博客

    相关文章

      网友评论

          本文标题:单例模式

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