Which Java Design Pattern fits best for if-else statement including loop?

后端 未结 4 790
攒了一身酷
攒了一身酷 2021-01-24 04:55

I have a use case with 7-8 if else. Sample use case:

 String type;
 List < Entity > entityList;


 if (type.equals(\"A\")) {
    ClassA a = new ClassA();
          


        
4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-24 05:27

    You need the following patterns to make this design generic -

    1. Factory Pattern - Make a BaseClass. Class A, B(and C...) should extend this BaseClass. BaseClass should have a single abstract method performTask() which should be implemented by Class A & Class B (and C...) to make them concrete implementations
    2. Template Pattern - Lets define a base class for the template - BaseTemplateClass. Now, the reason why I am using a template pattern here is that you have 3 distinct steps in the flow here -

      Step 1- Create a new instance of the BaseClass(we will use Factory defined in step 1 to do this). CreateInstance() will be the first concrete method in the TemplateBaseClass which will take in the string param identifier and call the factory. Since, this a fixed step we will keep CreateInstance() as a concrete method.

      Step 2 - BaseClass's performTask() will be called. This will be abstract.

      Step 3 - processEntityList() method will contain the for loop. This will also be a concrete method containing the call to the for loop - for (Entity e: entitylist){..}

      Lastly, we need a method execute() in BaseTemplateClass which calls the 3 methods defined in Steps 1, 2 & 3.

    An implementation of the BaseTemplateClass will have only the implementation of the abstract method performTask() as per its needs - in this case just invoking the A, B (or C...)'s performtask(). But this will be helpful if more needs to be done with A, B(or C...).

    The client(in classical terms) just needs to call execute() method of an instance of suitable implementation of BaseTemplateClass and rest will happen as per the design above.

提交回复
热议问题