单例的几种写法
来源:互联网 发布:贪心算法 最优合并 编辑:程序博客网 时间:2024/06/01 21:25
单例模式的运用十分广泛,下面给出单例模式的几种写法
1.懒汉
懒汉就意味着只在需要的时候才进行初始化,但是线程不安全
public class Singleton { private static Singleton instance; public static Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; }}
2.线程安全的懒汉
线程安全,但是效率低,毕竟进行一次初始化以后的同步锁定毫无意义。
public class Singleton { private static Singleton instance; public static synchronized Singleton getInstance(){ if(instance == null){ instance = new Singleton(); } return instance; }}
3.饿汉
饿汉在类加载的时候就会对static的instance完成初始化
public class Singleton { private static Singleton instance = new Singleton(); public static Singleton getInstance(){ return instance; }}
4.双重检验锁
两次校验,第二次加锁,可以避免初始化后同步效率低的问题。
public class Singleton { public volatile static Singleton instance; public static Singleton getSingleton(){ if(instance == null){ synchronized(Singleton.class){ if(instance == null){ instance = new Singleton(); } } } return instance; }}
单例模式的七种写法:http://cantellow.iteye.com/blog/838473
0 0
- 单例的几种写法
- 单例的几种写法
- 单例模式的几种写法
- 单例常见的几种写法
- 单例模式的几种写法
- ios 单例的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例的几种写法
- 单例模式的几种写法
- 单例模式、的几种写法
- 单例模式的几种写法
- 单例的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- 单例模式的几种写法
- Android自定义View(一)__坐标系
- centos安装图形桌面
- 一切都是对象
- C++primer第四版第四章数组与指针
- A1042. Shuffling Machine (20)
- 单例的几种写法
- 在这个不公平的世界,你要输得起。
- request对象的getScheme和getProtocol获取协议
- 资料链接
- java方法能自动生成000到999之间的一个字符
- laravel5.1权限模块
- poj 1088 (记忆化搜索)
- 自定义对话框的宽高
- Java标识符