Singleton instantiation

前端 未结 10 1623
我寻月下人不归
我寻月下人不归 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:47

    How about this approach for eradicating the static block:

    private static Map_en_US s_instance = new Map_en_US() {{init();}};
    

    It does the same thing, but is way neater.

    Explanation of this syntax:
    The outer set of braces creates an anonymous class.
    The inner set of braces is called an "instance block" - it fires during construction.
    This syntax is often incorrectly called the "double brace initializer" syntax, usually by those who don't understand what is going on.

    Also, note:
    m_ is a naming convention prefix for instance (ie member) fields.
    s_ is a naming convention prefix for class (ie static) fields.
    So I changed the name of the field to s_....

提交回复
热议问题