设计模式:单例
2016-12-15 00:00
92 查看
这里只说线程安全的单例模式。
public class Singleton { private static Singleton uniqueInstance; private Singleton() {} //看这里看这里。这里对性能还是影响比较大,下面贴出它的改进行。 public static synchronized Singleton getInstance() { if (uniqueInstance == null) { uniqueInstance = new Singleton(); } return uniqueInstance; } public String getDescription() { return "I'm a thread safe Singleton!"; } }
public class SingletonClient { public static void main(String[] args) { Singleton singleton = Singleton.getInstance(); System.out.println(singleton.getDescription()); } }
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; } }
相关文章推荐
- 设计模式:命令
- 设计模式:适配器
- 微信SDK使用demo
- jquery.datetimepicker 使用感悟
- mongo的密集索引与稀疏索引
- Chrome 扩展 SecureShell 删除指定 known host fingerprint
- 1613-3-傅溥衍 总结《2016年12月14日》【连续第七十五天总结】
- docker 出现 client is newer than server 的解决方案
- redis-game-transaction
- 向tomcat学习jmx
- 自己开发的一个轻量级的记录工具,欢迎拍砖,觉得有意思的可以一起来开发。
- C语言求ln2
- Virtualbox设置虚拟机访问外网以及主机访问虚拟机
- thrift入门教程
- vs2013编译OGRE::error c1060 compiler is out of heap space
- 微信小程序调查报告(二)-账号注册篇
- dataTables本地刷新数据解决只能初始化一次问题
- dataTables中文排序以及中英文混排乱序问题解决
- HP Onboard Administrator 固件升级
- 10种linux下磁盘快照方式恢复系统