五种单件模式之Singleton的实现方法详解
package singletonpattern;
public class Singleton1 {
private static Singleton1 uniqueInstance;
private Singleton1() {
}
public static Singleton1 getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton1();
}
return uniqueInstance;
}
}
但是以上方法并没有考虑到多线程的情况,如果是多线程,仍有可能创建多个实例,因此可以通过加锁和同步来实现多线程的单件模式,同步的缺点是效率大大降低:
代码如下:
package singletonpattern;
public class Singleton2 {
private static Singleton2 uniqueInstance;
private Singleton2() {
}
public static synchronized Singleton2 getInstance() {
if (uniqueInstance == null) {
uniqueInstance = new Singleton2();
}
return uniqueInstance;
}
}
还有一种方法是自动初始化,这样肯定不会造成多个实例,但是如果实际没有用到的话也会初始化实例,浪费了资源:
代码如下:
package singletonpattern;
public class Singleton3 {
private static Singleton3 uniqueInstance = new Singleton3();
private Singleton3() {
}
public static Singleton3 getInstance() {
return uniqueInstance;
}
}
public class Singleton5 {
private Singleton5(){
}
public static Singleton5 getInstance(){
return Nested.instance;
}
static class Nested{
static Singleton5 instance = new Singleton5();
}
}
package singletonpattern;
public class Singleton4 {
private volatile static Singleton4 uniqueInstance;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (uniqueInstance == null) {
synchronized (Singleton4.class) {
if (uniqueInstance == null) {
uniqueInstance = new Singleton4();
}
}
}
return uniqueInstance;
}
}
使用了双重保险,双重检查,当没有实例化的时候才进行加锁和同步。