Mastering the Strategy Pattern in Java: Real-World Spring Implementation
This article explains the Strategy (Policy) Pattern, illustrates its structure, and demonstrates a practical Spring-based implementation where different message types are processed by distinct strategy services, using an enum to map types to beans for flexible, interchangeable algorithms.
Concept
The Strategy Pattern, also known as the Policy Pattern, defines a family of algorithms, encapsulates each one, and makes them interchangeable; this allows algorithm changes without affecting the clients that use them.
Practical Application
Business scenario: the system needs to listen to multiple message types, updating a single Elasticsearch index. Different message types use different strategies to supplement data before updating Elasticsearch for merchant search and statistics.
The implementation combines the Spring framework, a simple factory, and the Strategy Pattern.
Service Interface
public interface GatherExecuteService {
/**
* Process the message body
* @param gatherDataVo
*/
boolean execute(GatherDataVo gatherDataVo);
}Strategy Implementations
Price strategy
@Service
public class PriceExecuteServiceImpl implements GatherExecuteService {
@Override
public boolean execute(GatherDataVo gatherDataVo) {
// ... implementation omitted
}
}Product strategy
@Service
public class ProductExecuteServiceImpl implements GatherExecuteService {
@Override
public boolean execute(GatherDataVo gatherDataVo) {
// ... implementation omitted
}
}Stock strategy
@Service
public class StockExecuteServiceImpl implements GatherExecuteService {
@Override
public boolean execute(GatherDataVo gatherDataVo) {
// ... implementation omitted
}
}Enum for Strategy Beans
@Getter
@AllArgsConstructor
public enum MessageTypeEnum {
PRODUCT(0, "productExecuteServiceImpl", "商品基本信息消息"),
PRICE(1, "priceExecuteServiceImpl", "价格消息"),
STOCK(2, "stockExecuteServiceImpl", "库存消息");
private int type;
private String service;
private String description;
public static String getServiceName(int type) {
for (MessageTypeEnum enumType : MessageTypeEnum.values()) {
if (enumType.getType() == type) {
return enumType.getService();
}
}
return null;
}
}Using the Strategies
// Retrieve the appropriate strategy bean based on message type
String serviceName = MessageTypeEnum.getServiceName(gatherDataVo.getMessageType());
if (StringUtils.isNotBlank(serviceName)) {
GatherExecuteService gatherExecuteService = (GatherExecuteService) SpringContextUtil.getBean(
serviceName, GatherExecuteService.class);
// execute the strategy
}The Strategy Pattern is a simple design pattern often combined with other patterns in real projects; this example shares a practical usage.
JD Tech Talk
Official JD Tech public account delivering best practices and technology innovation.
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.
