单例实现

方案一:

public class SingleInstanceTest {

    private static volatile SingleInstanceTest mInstance;

    private SingleInstanceTest(){

    }

    public static SingleInstanceTest getInstance(){
        if (mInstance == null){
            synchronized (SingleInstanceTest.class){
                if (mInstance == null){
                    mInstance = new SingleInstanceTest();
                }
            }
        }
        return mInstance;
    }

    public void myMethod(){

    }

}

方案二:

public enum SingleInstanceEnum {

    INSTANCE;

    public void myMethod(){

    }

}
SingleInstanceEnum.INSTANCE.myMethod();

 

你可能感兴趣的:(单例实现)