1. 程式人生 > >單例模式的兩種較好的實現方式

單例模式的兩種較好的實現方式

一:

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();
                }
            }
        }
        return 
instance; } } 二:
public class B {
    private B() {
    }

    private static class BHolder {
        private final static B instance = new B();
    }

    public static B getInstance() {
        return BHolder.instance;
    }
}