單例模式的兩種較好的實現方式
阿新 • • 發佈:2019-02-06
一:
public class A { private static A instance=null; private A(){ } public static A getInstance(){ if(instance==null){ synchronized(A.class){ if(instance==null){ instance=new A(); } } } returninstance; } } 二:
public class B { private B() { } private static class BHolder { private final static B instance = new B(); } public static B getInstance() { return BHolder.instance; } }