Strategy Design Pattern, Generics and TypeSafety

前端 未结 3 2237
忘掉有多难
忘掉有多难 2021-02-09 01:25

I want to create the following Strategy Pattern combined with Factory, but I want it to be typesafe. I have done the following till now:

public interface Parser&         


        
3条回答
  •  天命终不由人
    2021-02-09 01:50

    I applaud your desire to use the Strategy Pattern; +1 for that. I do think Ingo's comments are spot on.

    Just an additional comment (taken from Effective Java, 2nd Ed.):

        switch (parserType) {
            case APARSER:
                parser = new AParser();
                break;
        }
    

    To use Joshua Bloch's words, "this solution appears compact and even elegant." However it may also be fragile and difficult to maintain. In general, you should try not to switch on enum constants because whenever you do so, your code will break whenever you change the enum.

    This is exactly the right time to use an abstract method definition in your enum and place the desired code right there with the enum constant. Doing this guarantees that you never forget to add the needed enum associated code to your project and assures that whenever you add to your enum that your project won't break.

    In fact, if your goals allow for it, it may even be possible or adviseable to move the entire factory method to your enum and have your enum class implement the Strategy interface.

提交回复
热议问题