单例模式中,懒汉式和饿汉式的区别
2013-12-17 22:12
246 查看
饿汉式:
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉式:
public class Singleton{
private static Singleton singleton = null;
private Singleton (){}
public static synchronized synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
比较:
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的
推荐使用第一种 .
从实现方式来讲他们最大的区别就是懒汉式是延时加载,
他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建,
使用的场合根据具体环境和个人习惯吧
public class Singleton{
private static Singleton singleton = new Singleton ();
private Singleton (){}
public Singleton getInstance(){return singletion;}
}
懒汉式:
public class Singleton{
private static Singleton singleton = null;
private Singleton (){}
public static synchronized synchronized getInstance(){
if(singleton==null){
singleton = new Singleton();
}
return singleton;
}
}
比较:
饿汉式是线程安全的,在类创建的同时就已经创建好一个静态的对象供系统使用,以后不在改变
懒汉式如果在创建实例对象时不加上synchronized则会导致对对象的访问不是线程安全的
推荐使用第一种 .
从实现方式来讲他们最大的区别就是懒汉式是延时加载,
他是在需要的时候才创建对象,而饿汉式在虚拟机启动的时候就会创建,
使用的场合根据具体环境和个人习惯吧
相关文章推荐
- 命名对象继承2-验证Open*命名对象安全属性的传递
- 和借钱有关(二)
- SVN源码服务器搭建-详细教程
- 每日Ubuntu小技巧 - 使用Ubuntu拷贝CD和DVD光盘
- 技术
- Hello World!
- 代码分析二:泛型方法与反射
- HDU1527:取石子游戏(威佐夫博弈)
- 浅谈 Facade 模式
- 如果让Visual Studio 多个相关联的文件形成树形结构?
- 阔别三十天后每天一博客卷土重来——互动交流新思路(中)
- Python 处理数据库返回结果
- 数字逻辑复习第一天
- attachEvent、addEventListener、detachEvent、removeEventListener
- FusionCharts 使用手记
- icmpv6 checksum
- java 集合一个键对应多个值
- flex myeclipse安装.
- read方法读文件
- 回调、匿名函数、闭包在PHP中的应用