饿汉式
方式一:直接实例化饿汉式(简洁直观)
class Singleton1 {
private static final Singleton1 INSTANCE = new Singleton1();
private Singleton1(){
}
}
方式二:枚举式(最简洁)
enum Singleton2{
INSTANCE;
}
方式三:静态代码块饿汉式(适合复杂实例化)
class Singleton3{
public static final Singleton3 INSTANCE;
private String info;
static {
try {
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("single.properties");
Properties properties = new Properties();
properties.load(is);
INSTANCE = new Singleton3(properties.getProperty("info"));
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Singleton3(String info){
this.info = info;
}
}
懒汉式
方式四:线程不安全(适用于单线程)
class Singleton4 {
private static Singleton4 instance;
private Singleton4() {
}
public static Singleton4 getInstance() {
if (instance == null) {
instance = new Singleton4();
}
return instance;
}
}
方式五:线程安全(适用于多线程)
class Singleton5 {
private static Singleton5 instance;
private Singleton5() {
}
public static Singleton5 getInstance() {
if (instance == null) {
synchronized (Singleton5.class) {
if (instance == null) {
instance = new Singleton5();
}
}
}
return instance;
}
}
方式六:静态内部类形式(适用于多线程)
class Singleton6 {
private Singleton6(){
}
private static class Inner {
private static final Singleton6 INSTANCE = new Singleton6();
}
public static Singleton6 getInstance() {
return Inner.INSTANCE;
}
}