1.对于性能要求不高,可以这样写
public class Singleton_1 {
private static Singleton_1 uniqueInstance;
//其他变量
private Singleton_1(){}
public static synchronized Singleton_1 getInstance(){
if (uniqueInstance == null){
uniqueInstance = new Singleton_1();
}
return uniqueInstance;
}
//其他方法
}
2.静态初始化的方式,非动态实例化;适于创建和运行时负担不是太重,eagerly创建单例
public class Singleton_2 {
private static Singleton_2 uniqueInstance = new Singleton_2();
//其他变量
private Singleton_2(){}
public static synchronized Singleton_2 getInstance(){
return uniqueInstance;
}
//其他方法
}
3.双重检验加锁,从而减少使用synchronized(只有一次),提高性能
public class Singleton_3 {
private volatile static Singleton_3 uniqueInstance;//volatile关键字保证读取过程变量的值保持不变
//其他变量
private Singleton_3(){}
public static synchronized Singleton_3 getInstance(){
if (uniqueInstance == null){
synchronized (Singleton_3.class){
if (uniqueInstance == null){
uniqueInstance = new Singleton_3();
}
}
}
return uniqueInstance;
}
//其他方法
}
更多:如何正确地写出单例模式http://www.importnew.com/21141.html