Singleton Pattern 单例模式
2015-07-05 04:39
260 查看
Singleton Pattern: ensures a class has only one instance, and provides a global point of access to it.
Note: carefully deal with multithreading.
Synchronizing a method can decrease performance by a factor of 100.
1. Synchronize method
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}This has overhead. Lazy create. Only create instance when needed.
2. Eagerly create instance.
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return uniqueInstance;
}
}
Eager create. Create an instance even it is not used.
3. Use double-checking locking
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized(Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
This reduce the synchronize overhead. Use volatile to ensure no cached variable.
应用:设备驱动
Note: carefully deal with multithreading.
Synchronizing a method can decrease performance by a factor of 100.
1. Synchronize method
public class Singleton {
private static Singleton uniqueInstance;
private Singleton(){}
public static synchronized Singleton getInstance() {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
}This has overhead. Lazy create. Only create instance when needed.
2. Eagerly create instance.
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
private Singleton(){}
public static Singleton getInstance() {
return uniqueInstance;
}
}
Eager create. Create an instance even it is not used.
3. Use double-checking locking
public class Singleton {
private volatile static Singleton uniqueInstance;
private Singleton(){}
public static Singleton getInstance() {
if(uniqueInstance == null) {
synchronized(Singleton.class) {
if(uniqueInstance == null) {
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
}
This reduce the synchronize overhead. Use volatile to ensure no cached variable.
应用:设备驱动
相关文章推荐
- fans-rt 内存管理设计方案(1)引言
- phpmyadmin mysql Access denied for user 'root'@'localhost'问题解决
- 鸟哥的Linux私房菜-----13、账号管理
- 鸟哥的Linux私房菜-----12、学习使用Shell scripts
- AssetBundle.CreateFromFile的有趣事情
- MapReduce架构
- HDFS架构
- 泛型实践——体检套餐系统
- fans-rt 介绍(1)-什么是fans-rt
- 使用集合组织相关数据
- 合法字符串 【动态规划】
- 引用类型传递 ListView展示数据
- Python图像处理库:PIL中Image,ImageDraw等基本模块介绍
- Linux中用stat命令查看文件时3个时间点解析
- JAVA虚拟机的生命周期
- unity, itween 对不透明对象使用FadeTo需要先更换material
- 仪式感有时很必要
- 设置自动换行
- 密码加密的算法
- 1006--Java集合--操作集合的工具类:Collections