转载自http://blog.csdn.net/inslow/article/details/54235925
定义:保证一个类仅有一个实例,并提供一个访问它的全局访问点。Java中单例模式定义:“一个类有且仅有一个实例,并且自行实例化向整个系统提供。”
通过单例模式可以保证系统中一个类只有一个实例而且该实例易于外界访问,从而方便对实例个数的控制并节约系统资源。如果希望在系统中某个类的对象只能存在一个,单例模式是最好的解决方案。所谓一山不容二虎,一夫不容二妻,就是这个道理。
在Java中单例模式又叫Singleton模式,保证在Java应用程序中,一个类Class只有一个实例存在。Singleton模式主要有两种形式:
饿汉式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
public
class
Singleton {
//1.将构造方法私有化,不允许外部直接创建对象
private
Singleton(){
}
//2.创建类的唯一实例,使用private static修饰
private
static
Singleton instance=
new
Singleton();
//3.提供一个用于获取实例的方法,使用public static修饰
public
static
Singleton getInstance(){
return
instance;
}
}
|
懒汉式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
Singleton2 {
//1.将构造方式私有化,不允许外边直接创建对象
private
Singleton2(){
}
//2.声明类的唯一实例,使用private static修饰
private
static
Singleton2 instance;
//3.提供一个用于获取实例的方法,使用public static修饰
public
static
Singleton2 getInstance(){
if
(instance==
null
){
instance=
new
Singleton2();
}
return
instance;
}
}
|
测试类:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
public
class
Test {
public
static
void
main(String[] args) {
//饿汉模式
Singleton s1=Singleton.getInstance();
Singleton s2=Singleton.getInstance();
if
(s1==s2){
System.out.println(
"s1和s2是同一个实例"
);
}
else
{
System.out.println(
"s1和s2不是同一个实例"
);
}
//懒汉模式
Singleton2 s3=Singleton2.getInstance();
Singleton2 s4=Singleton2.getInstance();
if
(s3==s4){
System.out.println(
"s3和s4是同一个实例"
);
}
else
{
System.out.println(
"S3和s4不是同一个实例"
);
}
}
}
|
测试结果:
1
2
|
s1和s2是同一个实例
s3和s4是同一个实例
|
饿汉式VS懒汉式:
饿汉模式的特点是加载类时比较慢,但运行时获取对象的速度比较快,线程安全
懒汉模式的特点是加载类时比较快,但运行时获取对象的速度比较慢,线程不安全
PS:解决懒汉式线程不安全的方法,在懒汉式中将getInstance方法添加一个关键字synchronized。即优化后的懒汉式单例模式为:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
public
class
Singleton2 {
//1.将构造方式私有化,不允许外边直接创建对象
private
Singleton2(){
}
//2.声明类的唯一实例,使用private static修饰
private
static
Singleton2 instance;
//3.提供一个用于获取实例的方法,使用public static修饰
public
synchronized
static
Singleton2 getInstance(){
if
(instance==
null
){
instance=
new
Singleton2();
}
return
instance;
}
}
|