单例模式
来源:互联网 发布:jdk源码 编辑:程序博客网 时间:2024/06/11 08:01
1.饿汉模式
缺点:当加载该类时,静态方法也会被加载并生成一个对象占用内容,而这个对象不一定会使用,造成资源浪费;另外new SinletionTest()也无法获取构造函数异常;
public class SingletonTest { private SingletonTest(){} private static final SingletonTest instance = new SingletonTest(); public SingletonTest getInstance() return instance; }}
2.饱汉模式
解决了饿汉模式的缺点,但是当多线程时会引起冲突,比如第一个线程要获取对象时,if(instance ==null) 后,同时第二个线程进入判断并获取对象,而第一个线程继续执行会获取第二个对象,造成冲突
public class SingletonTest { private SingletonTest(){} private static SingletonTest instance = null; public SingletonTest getInstance(){ if(instance == null) { instance = new SingletonTest(); } return instance; }}
3.解决上述问题只需要给函数添加一个锁就可以了,但是造成性能低下,因为成了多线程了;
public class SingletonTest { private SingletonTest(){} private static SingletonTest instance =null; public synchronized SingletonTest getInstance(){ if(instance == null) { instance = new SingletonTest(); } return instance; }}
- 根据枚举设计单例模式(jdk1.6之后)
public enum SingleEnum { instance; public static void getInstance(){ System.out.println("get123"); }}//测试public class TestEnum{ public static void main(String args[]) { for(int i=0; i<10; i++){ SingleEnum.instance.getInstance(); } }}//打印结果get123get123get123get123get123get123get123get123get123get123
阅读全文
0 0
- 单例、单例模式
- 单例模式-多线程单例模式
- 单件模式(单例模式)
- 设计模式------单例模式
- 设计模式------单例模式
- 设计模式-单例模式
- 设计模式 - 单例模式
- 设计模式---单例模式
- 设计模式---单例模式
- PHP模式-单例模式
- 【设计模式】单例模式
- 设计模式-单例模式
- 设计模式----单例模式
- 设计模式--单例模式
- 设计模式-单例模式
- 单例模式(单子模式)
- 设计模式-单例模式
- [设计模式] 单例模式
- CString2char*
- Java注解
- bzoj1797: [Ahoi2009]Mincut 最小割
- 自定义RecyclerView添加下拉刷新和上拉加载功能
- UIPickerView的使用(二)
- 单例模式
- 实际案例--关于jquery的对象获取和字符串的截取
- 数据库设计三大范式全解
- java的枚举用法
- 坐标系旋转变换函数
- UIPickerView的使用(一)
- ttttt
- 关于导入web项目出现"javax.servlet.http.HttpServlet" was not found on the Java Build Path异常
- iOS AutoLayout的用法