How to Replace Complex if‑else with Strategy Pattern and Map‑Lambda in Java
This article demonstrates how to refactor a coupon‑type service by applying the Strategy pattern and a Map combined with Java 8 lambda expressions, eliminating bulky if‑else or switch statements while improving maintainability and readability.
This article introduces the concrete application of the Strategy pattern and how a Map with functional interfaces can more perfectly solve the if‑else problem.
Requirement
Recently a service was written that, based on a coupon's type resourceType and code resourceId, queries the grant type grantType and claim rules.
Implementation idea:
Determine which database table to query based on resourceType.
Query the grant type and rules from the corresponding table using resourceId.
Coupon types include Red Packet, Shopping Voucher, QQ Membership, and Takeaway Membership, each stored in a different table.
Initial if‑else / switch approach
switch(resourceType){
case "红包": // query red packet grant type
break;
case "购物券": // query shopping voucher grant type
break;
case "QQ会员":
break;
case "外卖会员":
break;
default:
logger.info("Cannot find grant type for resourceType");
break;
}Such a method becomes long and hard to read, and maintenance is difficult when many cases exist.
Strategy Pattern
The Strategy pattern extracts the conditional logic into separate classes, allowing each concrete strategy to be modified independently, improving maintainability.
Structure diagram:
Implementation using the Strategy pattern:
switch(resourceType){
case "红包":
String grantType = new Context(new RedPaper()).ContextInterface();
break;
case "购物券":
String grantType = new Context(new Shopping()).ContextInterface();
break;
// ... other cases
default:
logger.info("Cannot find grant type for resourceType");
break;
}Drawbacks: many strategies lead to many classes, and the overall dispatch logic is hard to view.
Map + Functional Interface
Using Java 8 lambda expressions, the condition becomes the map key and the business logic becomes the value, making the dispatch logic explicit and concise.
Requirement: based on coupon (resource) type resourceType and code resourceId , query the grant type grantType .
Service implementation:
@Service
public class QueryGrantTypeService {
@Autowired
private GrantTypeSerive grantTypeSerive;
private Map<String, Function<String,String>> grantTypeMap = new HashMap<>();
/**
* Initialize dispatch logic, replacing if‑else.
* key: coupon type
* value: lambda that returns the grant type
*/
@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, String resourceId){
Function<String,String> result = grantTypeMap.get(resourceType);
if(result != null){
return result.apply(resourceId);
}
return "查询不到该优惠券的发放方式";
}
}Business logic can be extracted into a separate service:
@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点开始秒杀";
}
}Controller example:
@RestController
public class GrantTypeController {
@Autowired
private QueryGrantTypeService queryGrantTypeService;
@PostMapping("/grantType")
public String test(String resourceName){
return queryGrantTypeService.getResult(resourceName);
}
}Drawbacks of the Map‑lambda approach: teammates must understand lambda expressions, which may be a learning barrier.
Conclusion
The Strategy pattern extracts conditional logic into separate classes, improving maintainability.
Using a Map with functional interfaces replaces if‑else dispatch, avoiding the proliferation of strategy classes and providing a clear overview of the business logic.
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.
Programmer DD
A tinkering programmer and author of "Spring Cloud Microservices in Action"
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.
