方式1:html
public class Something { private Something() {} private static class LazyHolder { private static final Something INSTANCE = new Something(); } public static Something getInstance() { return LazyHolder.INSTANCE; } }
方式2:java
public class Singleton { private static final Singleton INSTANCE = new Singleton(); private Singleton() {} public static Singleton getInstance() { return INSTANCE; } }
方式3:apache
public class Singleton { private static final Singleton instance; static { try { instance = new Singleton(); } catch (Exception e) { throw new RuntimeException("Darn, an error occurred!", e); } } public static Singleton getInstance() { return instance; } private Singleton() { // ... } }
方式4:api
public enum Singleton { INSTANCE; public void execute (String arg) { // Perform operation here } }
方式5:ide
public class SingletonDemo { private static volatile SingletonDemo instance; private SingletonDemo() { } public static SingletonDemo getInstance() { if (instance == null ) { synchronized (SingletonDemo.class) { if (instance == null) { instance = new SingletonDemo(); } } } return instance; } }
方式6:code
使用apache commons lang: LazyInitializerorm
public class ComplexObjectInitializer extends LazyInitializer<ComplexObject> { @Override protected ComplexObject initialize() { return new ComplexObject(); } } // Create an instance of the lazy initializer ComplexObjectInitializer initializer = new ComplexObjectInitializer(); ... // When the object is actually needed: ComplexObject cobj = initializer.get();
方式7:htm
使用guava:token
private static final Supplier<String> tokenSup = Suppliers.memoize(new Supplier<String>() { @Override public String get() { //do some init String result = xxx; return result; } });