Can I use the builder pattern on a Java Enum

前端 未结 3 981
粉色の甜心
粉色の甜心 2021-02-05 11:26

I\'m re-writing some code, and I\'ve decided the way to recreate the class, as there are a fixed number of sheets, I\'m creating them as enums. This is a decision based on the r

3条回答
  •  Happy的楠姐
    2021-02-05 11:42

    You can use instance blocks (often incorrectly called "double brace initializers") to customise construction with arbitrary code:

    public enum workBookSheet {
    
        mySheet1("Name1", "mainSheet1.xls", true, 1) {{
            addSubSheet("pathToSubSheet1.xls");
        }},
        mySheet2("Name2", "mainSheet2.xls", true, 2) {{
            // you can use the fluent interface:
            addHeaderSheet("pathToHeaders.xls").addSubSheet("pathtoSubSheet2.xls");
            // but I would prefer coding separate statements:
            addHeaderSheet("pathToHeaders.xls");
            addSubSheet("pathtoSubSheet2.xls");
        }};
    
        // rest of your class the same...
    }
    

    Employing this syntax allows you to work around the limitations imposed by an enum but still have the brevity, convenience and flexibility of a builder/fluent pattern.

提交回复
热议问题