五种实现方式:
在类加载到jvm初始化的时候创建对象,如果实例比较大,会影响性能。
class Singleton1{
private static final Singleton1 instance = new Singleton1();private Singleton1(){
}
public static Singleton1 getInstance(){
return instance;
}
}
//double check. 对Singleton2的class对象加锁。
class Singleton2{
private static Singleton2 instance;
private Singleton2(){
}
public static Singleton2 getInstance(){
if(instance == null){
synchronized(Singleton2.class){
if(instance == null){
instance = new Singleton2();
}
}
}
return instance;
}
}
//静态内部类使用,延迟实例化对象。在使用时创建而不是在类加载初始化创建。
class Singleton3{
private Singleton3(){
}
private static class Instance{
private static final Singleton3 instance = new Singleton3();
private Instance(){}
}
public static Singleton3 getInstance(){
return Instance.instance;
}
}
//can't clone and serializable.recommend use. 避免克隆和反序列化得到不同实例对象。
enum Singleton4{
INSTANCE;
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
return name;
}
}
//use in single thread 适用单线程
class Singleton5{
private static Singleton5 instance;
private Singleton5(){
}
public static Singleton5 getInstance(){
if(instance == null){
instance = new Singleton5();
}
return instance;
}
}
同步方法性能受到影响,适用于调用次数不多的情况。
class Singleton6{
private static Singleton6 instance;
private Singleton6(){
}
public static synchronized Singleton6 getInstance(){
if(instance == null){
instance = new Singleton6();
}
return instance;
}
}