1. 程式人生 > 其它 >使用策略設計模式+工廠模式+模板方法模式取代if else

使用策略設計模式+工廠模式+模板方法模式取代if else

筆記demo的git地址

關鍵點: InitializingBean和它的afterPropertiesSet()方法,抽象類

IT老哥講解的視訊地址

效果測試類

/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 22:23
*/

@SpringBootTest
public class TestServer {

   /**
    * 策略設計模式+工廠模式+模板方法模式 實現
    */
   @Test
   public void testDesign() {
       AbstractHandler handlerA = HandlerFactory.getInvokeStrategy("a");
       handlerA.methodA();
       AbstractHandler handlerB = HandlerFactory.getInvokeStrategy("b");
       System.out.println(handlerB.methodB());
       AbstractHandler handlerC = HandlerFactory.getInvokeStrategy("c");
       System.out.println(handlerC.methodB());
  }

   /**
    * if else 實現(簡單的邏輯判斷,建議使用)
    */
   @Test
   public void ifElse() {
       String str = "a";
       if (str.equals("a")) {
           System.out.println("處理a");
      } else if (str.equals("b")) {
           System.out.println("處理b");
      } else if (str.equals("c")) {
           System.out.println("處理c");
      }
  }
}

關鍵程式碼

抽象類
/**
* @author : lyn
* 技術點 :模板方法設計模式
* 可處理對於多種不同的返回邏輯
* @date : 2022/3/15 21:48
*/
public abstract class AbstractHandler implements InitializingBean {


   public void methodA(){
       //對於未重寫的,丟擲不支援操作異常
       throw new UnsupportedOperationException();
  }

   public String methodB(){
       throw new UnsupportedOperationException();
  }

}
兩個實現
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:55
*/
@Component
public class OneHandler extends AbstractHandler {

   @Override
   public void methodA() {
       System.out.println("處理邏輯a");
  }


   @Override
   public void afterPropertiesSet() throws Exception {
       HandlerFactory.register("a",this);
  }

}

 

/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:58
*/
@Component
public class ThreeHandler extends AbstractHandler {

   @Override
   public String methodB() {
       System.out.println("處理邏輯c");
       return "處理邏輯c";
  }

   @Override
   public void afterPropertiesSet() throws Exception {
       HandlerFactory.register("c",this);
  }
}
工廠類
/**
* @author : lyn
* 技術點 :
* @description:
* @date : 2022/3/15 21:59
*/
public class HandlerFactory {

   private static Map<String, AbstractHandler> strategyMap = new HashMap<>();

   public static AbstractHandler getInvokeStrategy(String str) {
       return strategyMap.get(str);
  }

   public static void register(String str, AbstractHandler handler) {
       if (StringUtils.isEmpty(str) || handler == null){
           return;
      }
       strategyMap.put(str, handler);
  }

}