单例模式:(Singleton)
确保一个类只有一个实例,并提供全局访问点。
示例代码:
public class Singleton {
private static Singleton uniqueInstance;
public static void main(String[] args) {
Singleton aSingleton = Singleton.getInstance();
System.out.println(aSingleton);
}
private Singleton(){}
public static Singleton getInstance() {
if( uniqueInstance == null )
uniqueInstance = new Singleton();
return uniqueInstance;
}
@Override
public String toString() {
return "This is a Singleton Instance.";
}
}
运行结果:
This is a Singleton Instance.
对单例模式的改进:
1. 对于多线程的改进
from:
public static Singleton getInstance()
to:
public static synchronized Singleton getInstance()
synchronized 迫使我们在进入方法之前,进行同步, 先要等待其他线程离开该方法后才能进入该方法。
但是缺点是同步的方法可能造成程序执行效率下降100倍。
2. 提前实例化
to:
public class Singleton {
private static Singleton uniqueInstance = new Singleton();
public static void main(String[] args) {
Singleton aSingleton = Singleton.getInstance();
System.out.println(aSingleton);
}
private Singleton(){}
public static synchronized Singleton getInstance() {
return uniqueInstance;
}
@Override
public String toString() {
return "This is a Singleton Instance.";
}
}
3. 双重检查加锁
to:
public class Singleton {
private volatile static Singleton uniqueInstance;
public static void main(String[] args) {
Singleton aSingleton = Singleton.getInstance();
System.out.println(aSingleton);
}
private Singleton(){}
public static Singleton getInstance() {
if ( uniqueInstance == null ){
synchronized (Singleton.class) {
if ( uniqueInstance == null ){
uniqueInstance = new Singleton();
}
}
}
return uniqueInstance;
}
@Override
public String toString() {
return "This is a Singleton Instance.";
}
}
如果没有实例还没有创建,才进行同步,那么只有一次同步,就是在创建第一个的实例的时候。