Java, Fuzz Buzz--Follow up(no if else, and extendable)
Last week, I was asked a follow up questions about FizzBuzz: how do you optimize your code to make it more concise and extendable. \n// I give out the first ver
Last week, I was asked a follow up questions about FizzBuzz: how do you optimize your code to make it more concise and extendable. \n// I give out the first version code as follows:\n   \n\n    //easy for gc\n    private String FIZZ = "Fizz";\n    private String BUZZ = "Buzz";\n    private String FIZZ_BUZZ = "FizzBuzz";\n    \n    public List<String> fizzBuzz(int n) {\n        List<String> res = new ArrayList();\n        for(int i = 1; i <= n; i++){\n            //remove if else, make code shorter\n            String temp = i % 15 == 0 ? FIZZ_BUZZ : (i % 3 == 0 ? FIZZ : (i % 5 == 0 ?  BUZZ : String.valueOf(i)));\n            res.add(temp);\n        }\n        return res;\n    }\n\nHowever, If there are more conditions, for example if i % 7 == 0 print xxx,  it seems our method is not convenient for extension, then I come up with using composite design pattern. The first thing I need is to design a action interface:\n\n~~~\ninterface Rule{\n     boolean apply(int i);\n}\n~~~\nThe multiple conditions are actually all kinds of rules. we use the following code to abstract our rule. \n\n~~~\n    private Map<Rule, String> ruleContainers = new HashMap();\n    private Set<Rule> rules  = new HashSet();\n\n    public RuleContainer() {\n        addRule(i -> i % 15 == 0, "FizzBuzz");\n        addRule(i -> i % 3 == 0, "Fizz");\n        addRule(i -> i % 5 == 0, "Buzz");\n    }\n\n    public void addRule(Rule rule, String res) {\n        rules.add(rule);\n        ruleContainers.put(rule, res);\n    }\n\n    public String getValue(int i) {\n        for (Rule rule : rules) {\n            if (rule.apply(i)) {\n                return ruleContainers.get(rule);\n            }\n        }\n        return String.valueOf(i);\n    }\n\n  //then the origin code should be as follows:\n   public List<String> fizzBuzz(int n) {\n        List<String> res = new ArrayList();\n        for(int i = 1; i <= n; i++){\n            res.add(getValue(i));\n        }\n        return res;\n    }\n~~~
[]