使用策略设计模式+工厂模式+模板方法模式取代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);
  }
?
}