java单例的几种实现方法
2015-08-31 20:38
441 查看
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; } });
相关文章推荐
- JAVA中转义字符
- Thinking in Java---线程通信+三种方式实现生产者消费者问题
- Spring整合JMS(三)——MessageConverter介绍
- ArcGIS for Android 在Eclipse上的安装配置 (下:安装配置篇)
- [JavaWeb基础] 015.Struts2 表单验证框架
- JDK与JRE的区别
- Java技术积累——用最原始的代码见证分页查询实现原理
- java 面向对象
- Java中的instanceof关键字
- 关于Java的一些小测试
- java安全沙箱(一)之ClassLoader双亲委派机制
- [转]spring security的原理及教程
- Eclipse下运行启动Heritrix1.14.4
- springMVC(6) springMVC静态文件访问
- java学习个人笔记---java内存管理之Java对象的引用方式
- java 假死诊断
- 3DES加密(C代码java重写)
- java多线程:线程范围内共享变量(四)
- JavaSE初学笔记之<nio的学习>
- Java蛇形数组的简单实现代码