单例模式的几种实现方法,具体如下:
public class Singleton{
private static Singleton instance;
private Singleton(){
}
public static Singleton getInstance(){
if(instance == null){
instance = new Singleton();
}
return instance;
}
}
public class Singleton {
private static Singleton instance = new Singleton();
private Singleton(){}
public static Singleton getInstance(){
return instance;
}
}
public class Singleton {
private static Singleton instance ;
private Singleton(){}
public static Singleton getInstance(){
if (instance == null){
synchronized (Singleton.class){
if (instance == null){
instance = new Singleton();
}
}
}
return instance;
}
}
public class Singleton {
private Singleton(){}
public static Singleton getInstance(){
return SingletonHolder.instance;
}
private static class SingletonHolder {
private static Singleton instance = new Singleton();
}
}
public class Singleton {
private static final String KEY = "instance";
private static Map<String, Singleton> map = new HashMap<>();
private Singleton(){}
public static Singleton getInstance(){
Singleton singleton ;
if (map.get(KEY) == null){
singleton = new Singleton();
map.put(KEY, singleton);
} else {
singleton = map.get(KEY);
}
return singleton;
}
}
public enum Singleton {
instance;
public void operate(){}
}
更多文章请移步我的博客:DevWiki Bolg