table of Contents
Singleton
To ensure that only one instance of any case
Hungry Chinese-style
public class Singleton {
//在类被加载的时候运行一次,这是本类构造函数的唯一一次使用。
//未被使用之前就已经实例化完成,称为饿汉式
private static Singleton singleton = new Singleton();
//构造函数为私有的,只有本类才能构造实例
private Singleton() {
System.out.println("生成了一个Singleton实例");
}
//外界只能通过唯一的getInstance方法获得这个唯一的实例
public static Singleton getInstance() {
return singleton;
}
}
Advantages: simple, no thread synchronization issues.
Disadvantages: Examples will always take up memory, a waste of space.
Lazy style
public class Singleton2 {
private static Singleton2 instance;
private Singleton2() {}
public static Singleton2 getInstance() {
//在别人需要的时候才开始实例化
if(instance == null) {
instance = new Singleton2();
}
return instance;
}
}
Advantages: instantiation deferred to the needs of the time, do not waste memory space.
Cons: thread safe
Thread-safe lazy style
public class Singleton3 {
private static Singleton3 instance;
private Singleton3() {}
public static Singleton3 getInstance() {
if(instance == null) {
//需要时创建,并且只对关键代码块加锁,保证性能
synchronized (Singleton3.class) {
if (instance == null) {
instance = new Singleton3();
}
}
}
return instance;
}
}
Advantages: deferred load, take up less space, thread-safe
Disadvantages: trouble