设计模式读书笔记-单件模式
单件模式- 确保一个类只有一个实例,全局只有一个入口点。
类如下:
public class Singleton {
private static Singleton uniqueInstance;
// other useful instance variables here
private Singleton() {}
public static Singleton getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton();
}
return uniqueInstance;
}
// other useful methods here
}
采用单件模式,主要解决整个程序中有些资源是共享的,如打印机等。
会发生的问题:解决多线程问题:
解决线程的三种方法:
1 采用同步方法
Public Static synchronized myClass getInstance()
{
Retuan new myClass();
};
但同步一个方法可能造成一个程序效率下降100倍,如果效率不是问题,这样就可以。
否则
2 使用“急切”创建实例
声明时创建 Private static myClass instance= new myClass();
3 “双重检查加锁“ (JAVA5 以上支持volatile关键字)
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;
}
}
所以单价模式是很简单的模式,实际中公用资源常被定义,注意解决多线程问题。
本文出自 “清风” 博客
相关新闻>>
- 发表评论
-
- 最新评论 进入详细评论页>>
今日头条
更多>>您可能感兴趣的文章
- winform下通过webclient使用非流方式上传(post)数据和
- Asp.net MVC源码分析--Model Validation(Client端)实现(2)
- 微软ASP.NET站点部署指南(11):部署SQL Server数据
- 教你如何来恢复一个丢失的数据文件
- ASP.NET数据格式的Format--DataFormatString
- MVC中一个表单实现多个提交按钮(一个action搞定
- asp.net js模拟Button点击事件
- 谈.Net委托与线程——创建无阻塞的异步调用(一
- Pro ASP.NET MVC 3 Framework学习笔记之九
- asp.net 六大内置对象(2)