单例
来源:互联网 发布:电力软件 编辑:程序博客网 时间:2024/04/29 21:27
第一种单例模型
class Singleton01{
private Singleton01(){}private static Singleton01 instance;
/**使用的对象锁为Singleton01.class*/
public static synchronized Singleton01 getInstance() {
if(instance==null){
instance=new Singleton01();
}
return instance;
}
//public void show(){}
}
第二种单例模型
private Singleton02(){}
private static Singleton02 instance;
/**使用的对象锁为Singleton01.class*/
public static Singleton02 getInstance() {
if(instance==null){
synchronized (Singleton02.class) {
if(instance==null){
instance=new Singleton02();
}
}
}
return instance;
}
//public void show(){}
}
第三种单例模型
class Singleton03{//饿汉单例 (小对象,频繁用)
private Singleton03() {}/**类加载时初始化此属性*/
private static Singleton03 instance=new Singleton03();
public static Singleton03 getInstance() {
return instance;
}
//public static void display(){}
//public void show(){}
}
第四种单例模型
class Singleton04{
private Singleton04(){}
/**采用此内部类延迟Singleton04对象的创建,何时需要何时创建,
* 是Singleton03此方案一种优化*/
private static class Inner{
static Singleton04 instance=
new Singleton04();
}
public static Singleton04 getInstance(){
return Inner.instance;
}
public static void display(){}
//public void show(){}
}
第五种单例模型
enum Singleton05{//特殊的类型,Singleton05.class
instance;//对象(类加载时创建)
public void show(){}
}
0 0
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- 单例
- LeetCode 338. Counting Bits
- CentOS tcpflow抓包
- A*B Problem II
- leetcode-python 第五周
- 浏览器打开应用指定的界面
- 单例
- STL map的用法介绍!
- Android—AlertDialog提示信息
- 解决异步获取user session的方法
- SharedPreferences判断是否第一次进入程序
- hdu 4438 Hunters【数学水题】
- Gson选择性排除序列化字段
- Android Service基础之Bound Services
- Linux命令速查手册