// 饱汉 // UnThreadSafe public class Singleton1 { private static Singleton1 singleton = null; private Singleton1() { } public static Singleton1 getInstance() { if (singleton == null) { singleton = new Singleton1(); } return singleton; } }
// 饱汉 // ThreadSafe public class Singleton1_1 { private static Singleton1_1 singleton = null; private Singleton1_1() { } public synchronized static Singleton1_1 getInstance() { if (singleton == null) { singleton = new Singleton1_1(); } return singleton; } }
// 饱汉 // UnThreadSafe public class Singleton1_2 { private static Singleton1_2 singleton = null; public int f1 = 1; // 触发部分初始化问题 public int f2 = 2; private Singleton1_2() { } public static Singleton1_2 getInstance() { // may get half object if (singleton == null) { synchronized (Singleton1_2.class) { if (singleton == null) { singleton = new Singleton1_2(); } } } return singleton; } }
// 饱汉 // ThreadSafe public class Singleton1_3 { private static volatile Singleton1_3 singleton = null; public int f1 = 1; // 触发部分初始化问题 public int f2 = 2; private Singleton1_3() { } public static Singleton1_3 getInstance() { if (singleton == null) { synchronized (Singleton1_3.class) { // must be a complete instance if (singleton == null) { singleton = new Singleton1_3(); } } } return singleton; } }
// 饿汉 // ThreadSafe public class Singleton2 { private static final Singleton2 singleton = new Singleton2(); private Singleton2() { } public static Singleton2 getInstance() { return singleton; } }
// Holder模式 // ThreadSafe public class Singleton3 { private static class SingletonHolder { private static final Singleton3 singleton = new Singleton3(); private SingletonHolder() { } } private Singleton3() { } /** * 勘误:多写了个synchronized。。 public synchronized static Singleton3 getInstance() { return SingletonHolder.singleton; } */ public static Singleton3 getInstance() { return SingletonHolder.singleton; } }
// 枚举 // ThreadSafe public enum Singleton4 { SINGLETON; }
// 枚举 // ThreadSafe public class Singleton4 extends Enum<Singleton4> { ... public static final Singleton4 SINGLETON = new Singleton4(); ... }
// 枚举 // ThreadSafe public enum Singleton4_1 { SINGLETON("enum is the easiest singleton pattern, but not the most readable") { public void testAbsMethod() { print(); System.out.println("enum is ugly, but so flexible to make lots of trick"); } }; private String comment = null; Singleton4_1(String comment) { this.comment = comment; } public void print() { System.out.println("comment=" comment); } abstract public void testAbsMethod(); public static Singleton4_1 getInstance() { return SINGLETON; } }