Singleton instantiation

前端 未结 10 1596
我寻月下人不归
我寻月下人不归 2020-12-05 05:40

Below show is the creation on the singleton object.

public class Map_en_US extends mapTree {

    private static Map_en_US m_instance;

    private Map_en_US         


        
10条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-05 05:59

    static block is here to allow for init invocation. Other way to code it could be eg like this (which to prefer is a matter of taste)

    public class Map_en_US extends mapTree {
    
        private static
                /* thread safe without final,
                   see VM spec 2nd ed 2.17.15 */
                Map_en_US m_instance = createAndInit();
    
        private Map_en_US() {}
    
        public static Map_en_US getInstance(){
            return m_instance;
        }
    
        @Override
        protected void init() {
            //some code;
        }
    
        private static Map_en_US createAndInit() {
            final Map_en_US tmp = new Map_en_US();
            tmp.init();
            return tmp;
        }
    }
    

    update corrected per VM spec 2.17.5, details in comments

提交回复
热议问题