BlessingCR’s Blog
BlessingCR’s Blog

策略模式--替代if-else

用于取代以下代码

switch(resourceType){

 case "红包": 

  String grantType=new Context(new RedPaper()).ContextInterface();

  break;

 case "购物券": 

  String grantType=new Context(new Shopping()).ContextInterface();

  break;

 ......

 default : logger.info("查找不到该优惠券类型resourceType以及对应的派发方式");

  break;

实现方式:

@Service

public class GrantTypeService {

   public String redPaper(String resourceId){

       //红包的发放方式

       return "每周末9点发放";

   }

   public String shopping(String resourceId){

       //购物券的发放方式

       return "每周三9点发放";

   }

   public String QQVip(String resourceId){

       //qq会员的发放方式

       return "每周一0点开始秒杀";

   }

}

@Service

public class QueryGrantTypeService {

   @Autowired

   private GrantTypeService grantTypeSerive;

   private Map<String, Function<String,String>> grantTypeMap=new ConcurrentHashMap<>();

   /**

    *  初始化业务分派逻辑,代替了if-else部分

    *  key: 优惠券类型

    *  value: lambda表达式,最终会获得该优惠券的发放方式

    */

   @PostConstruct

   public void dispatcherInit(){

        grantTypeMap.put("红包",resourceId->grantTypeSerive.redPaper(resourceId));

        grantTypeMap.put("购物券",resourceId->grantTypeSerive.shopping(resourceId));

        grantTypeMap.put("qq会员",resourceId->grantTypeSerive.QQVip(resourceId));

   }

   public String getResult(String resourceType){

       //Controller根据 优惠券类型resourceType、编码resourceId 去查询 发放方式grantType

       Function<String,String> result=grantTypeMap.get(resourceType);

       if(result!=null){

           //传入resourceId 执行这段表达式获得String型的grantType

           return result.apply(resourceType);

       }

       return "查询不到该优惠券的发放方式";

   }

}

发表回复

textsms
account_circle
email

  • A person essentially help to make seriously articles I would state. This is the first time I frequented your website page and thus far? I amazed with the research you made to make this particular publish incredible. Excellent job!

    8 月前 回复

BlessingCR’s Blog

策略模式--替代if-else
用于取代以下代码 switch(resourceType){  case "红包":    String grantType=new Context(new RedPaper()).ContextInterface();   break; …
扫描二维码继续阅读
2023-02-21