Replace Long if‑else Chains with Strategy Pattern or Map‑Lambda in Java
This article explains how to design a Java service that selects the appropriate coupon grant type based on resource type and ID, comparing traditional switch/if‑else, the Strategy pattern, and a concise Map‑lambda approach while showing code examples and trade‑offs.
Requirement
We need a service that, given a coupon type (resourceType) and its identifier (resourceId), returns the grant type and the receiving rules.
Naïve if‑else / switch
Using a long switch or if‑else makes the method large and hard to maintain, especially when each case contains many lines of logic.
switch(resourceType){
case "红包": // query red‑paper grant type
break;
case "购物券": // query shopping‑coupon grant type
break;
// ...
default: logger.info("Cannot find coupon type");
}Strategy Pattern
The strategy pattern extracts each case’s logic into a separate class that implements a common interface, improving maintainability.
switch(resourceType){
case "红包":
String grantType = new Context(new RedPaper()).ContextInterface();
break;
case "购物券":
String grantType = new Context(new Shopping()).ContextInterface();
break;
// ...
}Drawbacks: many concrete strategy classes are needed and the overall dispatch logic is still hidden.
Map + Functional Interface (Java 8)
Using a Map<String, Function<String,String>> where the key is the coupon type and the value is a lambda that returns the grant type makes the dispatch table explicit.
@Service
public class QueryGrantTypeService {
@Autowired
private GrantTypeSerive grantTypeSerive;
private Map<String, Function<String,String>> grantTypeMap = new HashMap<>();
@PostConstruct
public void dispatcherInit(){
grantTypeMap.put("红包", id -> grantTypeSerive.redPaper(id));
grantTypeMap.put("购物券", id -> grantTypeSerive.shopping(id));
grantTypeMap.put("qq会员", id -> grantTypeSerive.QQVip(id));
}
public String getResult(String resourceType, String resourceId){
Function<String,String> fn = grantTypeMap.get(resourceType);
if(fn != null){
return fn.apply(resourceId);
}
return "查询不到该优惠券的发放方式";
}
}The service methods that contain the actual business logic are kept in a separate GrantTypeSerive class.
@Service
public class GrantTypeSerive {
public String redPaper(String resourceId){ return "每周末9点发放"; }
public String shopping(String resourceId){ return "每周三9点发放"; }
public String QQVip(String resourceId){ return "每周一0点开始秒杀"; }
}A simple controller calls queryGrantTypeService.getResult(...) to obtain the grant type.
Summary
Strategy pattern moves each branch into its own class, improving maintainability but increasing class count. The Map‑lambda approach makes the dispatch table visible, reduces boilerplate, and avoids the proliferation of strategy classes, though it requires team familiarity with Java 8 lambda syntax.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
