Head First 设计模式学习笔记(五)单例模式
单例模式,都是线程安全的。虽然例1不是绝对安全.
?
例1、
public class Singleton {private static Singleton uniqueInstance; private Singleton() {} public static synchronized Singleton getInstance() {if (uniqueInstance == null) {uniqueInstance = new Singleton();}return uniqueInstance;} }?
例2、
public class Singleton {private volatile static Singleton uniqueInstance; private Singleton() {} public static Singleton getInstance() {if (uniqueInstance == null) {synchronized (Singleton.class) {if (uniqueInstance == null) {uniqueInstance = new Singleton();}}}return uniqueInstance;}}?例3、
?
public class Singleton {private static Singleton uniqueInstance = new Singleton(); private Singleton() {} public static Singleton getInstance() {return uniqueInstance;}}