java单例设计模式

单例设计模式 懒汉式/饿汉式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class //懒汉式的(多线程)安全定义方法(面试常考)
{
private static Single s=null;
private (){}
public static Single getInstance()
{
if(a==null)
{
synchronized(Single.class)
{
if(s==null)
s=new Single();
}
}
return s;
}
}
1
2
3
4
5
6
7
8
class //饿汉式(开发中常用)
{
private static final Single s=new Single();
private static Single getInstance()
{
return s;
}
}