Backend Development 10 min read

Using the Strategy Pattern to Simplify Complex if‑else Logic in Order Processing with Java Spring Boot

This article demonstrates how to replace verbose if‑else statements in an order‑processing system with a clean Strategy Pattern implementation, using custom annotations, a handler context, and Spring Boot components, providing complete code examples and a concise summary of the approach.

Top Architect
Top Architect
Top Architect
Using the Strategy Pattern to Simplify Complex if‑else Logic in Order Processing with Java Spring Boot

Requirement

A virtual business requirement is introduced: an order system must handle different order types (normal, group, promotion) with distinct processing logic.

Project Structure

The overall module layout is shown (image omitted for brevity).

Order Entity

/**
 * 订单实体
 */
public class OrderDTO {
    private String code;
    private BigDecimal price;
    /*
     * 订单类型:
     * 1:普通订单
     * 2:团购订单
     * 3:促销订单
     */
    private String type;
    // getter, setter 自己实现
}

Service Interface

/**
 * 订单处理
 */
public interface IOrderService {
    /**
     * 根据订单的不同类型做出不同的处理
     * @param dto 订单实体
     * @return 为了简单,返回字符串
     */
    String orderHandler(OrderDTO dto);
}

@Component
public class OrderServiceImpl implements IOrderService {
    @Override
    public String orderHandler(OrderDTO dto) {
        if ("1".equals(dto.getType())) {
            // 普通订单处理
        } else if ("2".equals(dto.getType())) {
            // 团购订单处理
        } else if ("3".equals(dto.getType())) {
            // 促销订单处理
        }
        // 未来订单类型增加
    }
}

@Component
public class OrderServiceImpl implements IOrderService {
    @Autowired
    private HandlerContext handlerContext;
    @Override
    public String orderHandler(OrderDTO dto) {
        /*
         * 1:使用 if..else 实现
         * 2:使用策略模式实现
         */
        AOrderTypeHandler instance = handlerContext.getInstance(dto.getType());
        return instance.handler(dto);
    }
}

Using the Strategy Pattern reduces the handling code to two lines (retrieving the handler from the context and invoking it).

Handler Context and Processor

/**
 * 订单策略模式环境
 * 这个类的注入由 HandlerProccessor 实现
 */
public class HandlerContext {
    private Map
handlerMap;
    /**
     * 构造传参不能直接使用注解扫入
     */
    public HandlerContext(Map
handlerMap) {
        this.handlerMap = handlerMap;
    }
    /**
     * 获得实例
     * @param type
     * @return
     */
    public AOrderTypeHandler getInstance(String type) {
        if (type == null) {
            throw new IllegalArgumentException("type 参数不能为空");
        }
        AOrderTypeHandler clazz = handlerMap.get(type);
        if (clazz == null) {
            throw new IllegalArgumentException("该类型没有在枚举 OrderTypeHandlerAnno 中定义,请定义:" + type);
        }
        return clazz;
    }
}

@Component
public class HandlerProccessor implements BeanFactoryPostProcessor {
    /**
     * 扫描 @OrderTypeHandlerAnno 注解,初始化 HandlerContext,将其注册到 spring 容器
     */
    @Override
    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        Map
handlerMap = new HashMap<>();
        for (OrderTypeEnum temp : OrderTypeEnum.values()) {
            AOrderTypeHandler beanInstacle = getBeansWithAnnotation(beanFactory, AOrderTypeHandler.class, OrderTypeHandlerAnno.class, temp.getCode());
            handlerMap.put(temp.getCode(), beanInstacle);
        }
        HandlerContext context = new HandlerContext(handlerMap);
        // 单例注入
        beanFactory.registerSingleton(HandlerContext.class.getName(), context);
    }
    private
T getBeansWithAnnotation(ConfigurableListableBeanFactory beanFactory, Class
manager, Class
annotation, String code) throws BeansException {
        if (ObjectUtils.isEmpty(code)) {
            throw new RuntimeException("code is null ");
        }
        Collection
tCollection = beanFactory.getBeansOfType(manager).values();
        for (T t : tCollection) {
            OrderTypeHandlerAnno orderTypeHandlerAnno = t.getClass().getAnnotation(annotation);
            if (ObjectUtils.isEmpty(orderTypeHandlerAnno)) {
                throw new RuntimeException("该注解没有写入值 :" + code);
            }
            if (code.equals(orderTypeHandlerAnno.value().getCode())) {
                return t;
            }
        }
        throw new RuntimeException("通过 code 没有找到该注解对应的实体类 :" + code);
    }
}

Abstract Handler, Annotation and Enum

/**
 * 订单类型处理定义
 * 使用抽象类,那么子类就只有一个继承了
 */
public abstract class AOrderTypeHandler {
    /**
     * 一个订单类型做一件事
     * @param dto 订单实体
     * @return 为了简单,返回字符串
     */
    public abstract String handler(OrderDTO dto);
}

/**
 * 订单类型注解
 * 使用方式:
 * 1:普通订单 @OrderTypeHandlerAnno("1")
 * 2:团购订单 @OrderTypeHandlerAnno("2")
 * 3:促销订单 @OrderTypeHandlerAnno("3")
 */
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
public @interface OrderTypeHandlerAnno {
    OrderTypeEnum value();
}

public enum OrderTypeEnum {
    Normal("1", "普通"),
    Group("2", "团队"),
    Promotion("3", "促销");
    private String code;
    private String name;
    OrderTypeEnum(String code, String name) {
        this.code = code;
        this.name = name;
    }
    public String getCode() { return code; }
    public String getName() { return name; }
    public static String getNameByCode(String code) {
        for (OrderTypeEnum temp : OrderTypeEnum.values()) {
            if (temp.getCode().equals(code)) {
                return temp.getName();
            }
        }
        return null;
    }
}

Concrete Handlers

// 业务代码
/**
 * 普通订单处理
 */
@Component
@OrderTypeHandlerAnno(OrderTypeEnum.Normal)
public class NormalOrderHandler extends AOrderTypeHandler {
    @Override
    public String handler(OrderDTO dto) {
        return "处理普通订单";
    }
}

/**
 * 团购订单处理
 */
@Component
@OrderTypeHandlerAnno(OrderTypeEnum.Group)
public class GroupOrderHandler extends AOrderTypeHandler {
    @Override
    public String handler(OrderDTO dto) {
        return "处理团队订单";
    }
}

/**
 * 促销订单处理
 */
@Component
@OrderTypeHandlerAnno(OrderTypeEnum.Promotion)
public class PromotionOrderHandler extends AOrderTypeHandler {
    @Override
    public String handler(OrderDTO dto) {
        return "处理促销订单";
    }
}

Controller Example

@RestController
public class StrategyController {
    @Resource(name = "orderServiceImpl")
    private IOrderService orderService;
    @GetMapping("/api/order")
    @ResponseBody
    public String orderSave(OrderDTO dto) {
        String str = orderService.orderHandler(dto);
        return "{\"status\":1,\"msg\":\"保存成功\",\"data\":\"" + str + "\"}";
    }
}

Summary: By applying the Strategy Pattern together with custom annotations and a self‑registered handler context, the code eliminates cumbersome if‑else branches, improves maintainability, and makes it easy to extend the system for new order types.

Design PatternsJavastrategy patternbackend-developmentorder processingSpring Boot
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.