Backend Development 9 min read

Using Strategy Pattern and Map with Functional Interfaces to Replace if‑else in Java Backend Services

This article demonstrates how to apply the Strategy pattern and a Map of Java 8 lambda expressions to replace lengthy if‑else or switch statements when dispatching business logic for different coupon types, improving maintainability and readability of backend code.

Top Architect
Top Architect
Top Architect
Using Strategy Pattern and Map with Functional Interfaces to Replace if‑else in Java Backend Services

The article introduces a real‑world requirement: based on a coupon's resourceType and resourceId , the system must query the grant type and claim rules. Traditional implementations use long if‑else or switch blocks, which become hard to read and maintain.

Strategy Pattern – The pattern extracts each conditional branch into a separate class that implements a common interface. The client selects the appropriate implementation at runtime, reducing the size of a single method and isolating changes to individual classes.

Example of a classic switch (simplified):

switch(resourceType){
  case "红包":
    // query red‑paper grant type
    break;
  case "购物券":
    // query shopping‑coupon grant type
    break;
  // ... other cases ...
  default:
    logger.info("Cannot find grant type for resourceType");
    break;
}

Using the Strategy pattern with a Context class:

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;
}

While the Strategy pattern improves maintainability, it still requires a separate class for each coupon type, which can lead to class explosion.

Map + Functional Interface – By leveraging Java 8 lambda expressions, the conditional logic is stored in a Map<String, Function<String, String>> . The key is the resourceType , and the value is a lambda that returns the grant type for a given resourceId . This approach makes the dispatch table explicit and easy to extend.

Initialization of the map:

@Service
public class QueryGrantTypeService {
    @Autowired
    private GrantTypeSerive grantTypeSerive;
    private Map
> grantTypeMap = new HashMap<>();

    /** Initialize business dispatch logic, replacing the if‑else part */
    @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
fn = grantTypeMap.get(resourceType);
        if(fn != null){
            return fn.apply(resourceId);
        }
        return "查询不到该优惠券的发放方式";
    }
}

Service that contains the actual business logic:

@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 exposing the endpoint:

@RestController
public class GrantTypeController {
    @Autowired
    private QueryGrantTypeService queryGrantTypeService;

    @PostMapping("/grantType")
    public String test(String resourceName, String resourceId){
        return queryGrantTypeService.getResult(resourceName, resourceId);
    }
}

Both approaches solve the original problem, but the Map‑based solution avoids the proliferation of strategy classes and provides a clear, searchable dispatch table. The article concludes by summarizing the advantages and drawbacks of each method.

Backenddesign patternsJavaStrategy PatternmapFunctional Interface
Top Architect
Written by

Top Architect

Top Architect focuses on sharing practical architecture knowledge, covering enterprise, system, website, large‑scale distributed, and high‑availability architectures, plus architecture adjustments using internet technologies. We welcome idea‑driven, sharing‑oriented architects to exchange and learn together.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.