• java单例的几种实现方法


    java单例的几种实现方法:

    方式1:

    public class Something {
        private Something() {}
    
        private static class LazyHolder {
            private static final Something INSTANCE = new Something();
        }
    
        public static Something getInstance() {
            return LazyHolder.INSTANCE;
        }
    }
    

    方式2:

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

    方式3:

    public class Singleton {
        private static final Singleton instance;
    
        static {
            try {
                instance = new Singleton();
            } catch (Exception e) {
                throw new RuntimeException("Darn, an error occurred!", e);
            }
        }
    
        public static Singleton getInstance() {
            return instance;
        }
    
        private Singleton() {
            // ...
        }
    }
    

    方式4:

    public enum Singleton {
        INSTANCE;
        public void execute (String arg) {
            // Perform operation here 
        }
    }
    

    方式5:

    public class SingletonDemo {
        private static volatile SingletonDemo instance;
        private SingletonDemo() { }
    
        public static SingletonDemo getInstance() {
            if (instance == null ) {
                synchronized (SingletonDemo.class) {
                    if (instance == null) {
                        instance = new SingletonDemo();
                    }
                }
            }
    
            return instance;
        }
    }
    

    方式6:

    使用apache commons lang: LazyInitializer

     public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> {
         @Override
         protected ComplexObject initialize() {
             return new ComplexObject();
         }
     }
    
     // Create an instance of the lazy initializer
     ComplexObjectInitializer initializer = new ComplexObjectInitializer();
     ...
     // When the object is actually needed:
     ComplexObject cobj = initializer.get();
    

    方式7:

    使用guava:

     private static final Supplier<String> tokenSup = Suppliers.memoize(new Supplier<String>() {
            @Override
            public String get() {
            	//do some init
            	String result = xxx;
                return result;
            }
        });
  • 相关阅读:
    ES5特性Object.seal
    自定义右键菜单中bug记录
    ie9及以下不兼容event.target.dataset对象
    创建一个新数组并指定数组的长度
    vue组件的配置属性
    前端模板引擎和网络协议分类
    Python查询Mysql时返回字典结构的代码
    Python实现计算圆周率π的值到任意位的方法示例
    Python实现计算圆周率π的值到任意位的方法示例
    Python实现的计算马氏距离算法示例
  • 原文地址:https://www.cnblogs.com/rollenholt/p/4774063.html
Copyright © 2020-2023  润新知