设计模式-单件模式
来源:互联网 发布:linux 进程调度命令 编辑:程序博客网 时间:2024/05/21 06:52
经典的单件:
public class Singleton
{
private static Singleton uniqueInstance;
private Singleton() {}
public static Singleton getInstance()
{
if(uniqueInstance == null)
uniqueInstance = new Singleton();
return uniqueInstance ;
}
//这里是其他的有用方法
}
处理多线程:
1.变成同步(synchronized)方法,但耗性能
public class Singleton
{
private static Singleton uniqueInstance;
private Singleton() {}
public static synchronized Singleton getInstance()
{
if(uniqueInstance == null)
uniqueInstance = new Singleton();
return uniqueInstance ;
}
//这里是其他的有用方法
}
2.使用“急切”创建实例,而不是延迟实例化的做法public class Singleton
{
private static Singleton uniqueInstance = new Singleton();
private Singleton() {}
public static Singleton getInstance()
{
return uniqueInstance ;
}
//这里是其他的有用方法
}
3.用“双重检查加锁”,在getInstance()中减少使用同步,只有第一次会进行同步
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 ;
}
//这里是其他的有用方法
}
volatile 关键词确保,当uniqueInstance 变量被初始化成Singleton实例时,多个线程正确地处理uniqueInstance 变量
程序退出时,确保单例为null:
// Ensure that the instance is destroyed when the game is stopped in the editor.
void OnApplicationQuit()
{
s_Instance = null;
}
- 设计模式-单件
- 【设计模式】单件
- 设计模式---单件
- 设计模式------单件模式
- 设计模式--单件模式
- 设计模式 -- 单件模式
- 设计模式:单件模式
- 设计模式-单件模式
- 设计模式-单件模式
- 设计模式 单件模式
- 设计模式:单件模式
- 设计模式----单件模式
- 设计模式--单件模式
- 设计模式-单件模式
- 设计模式--单件模式
- 设计模式:单件模式
- 设计模式 ----- 单件模式
- 设计模式-单件模式
- 【Spark亚太研究院系列丛书】Spark实战高手之路-第一章 构建Spark集群(第五步)(8)
- eclipse启动tomcat, http://localhost:8080无法访问
- 漫谈程序员系列:谁是为加班而生的
- iphone6屏幕适配
- Java 队列
- 设计模式-单件模式
- ANT命令总结
- 数据结构——单链表的基本操作
- android开发工具
- iOS 高级开发技巧 1.熟悉Objective-C (四) 多用类型常量 少用#define预处理命令
- javaweb-通过servlet获取请求参数
- ScrollView嵌套ListView会出现的ListView底部会自动出现在屏幕上
- Google技术之 mod_Pagespeed 网页优化探索(1)
- Android: shape,selector,layer-list辨析