Strategy Pattern in Java: Theory, Advantages, Drawbacks, and Practical Payment Service Implementation

This article explains the Strategy design pattern, its structure, advantages and drawbacks, and demonstrates a practical Java implementation for payment processing using Spring beans, including interface definitions, concrete payment strategies, and a controller that selects the appropriate strategy at runtime.

Selected Java Interview Questions
Selected Java Interview Questions
Selected Java Interview Questions
Strategy Pattern in Java: Theory, Advantages, Drawbacks, and Practical Payment Service Implementation

What is the Strategy Pattern?

The Strategy pattern defines a family of interchangeable algorithms (strategies) that can be selected at runtime based on the context, allowing an object to change its behavior without modifying its code.

It requires a strategy interface and multiple concrete implementations, promoting programming to an interface rather than an implementation.

Advantages

Eliminates complex if / switch statements.

Code becomes elegant, reusable, and readable.

Follows the Open/Closed principle, improving extensibility and maintainability.

Disadvantages

When many strategies exist, the number of classes can grow significantly.

Clients must be aware of all available strategy classes and their purposes.

Strategy Pattern in Practice

Consider a payment selection scenario where a user can choose among several payment methods (Alipay, WeChat Pay, UnionPay, etc.). Using a simple if/else chain would become unwieldy, especially when new methods are added. The Strategy pattern solves this by defining a common payment interface and concrete strategy classes for each method.

1. Define the Strategy Interface

/**
 * @author fei
 * @version 1.0
 * @title 支付接口
 */
public interface IPayment {
    /**
     * 支付
     * @param order
     * @return PayResult
     */
    PayResult pay(Order order);
}

2. Define Supporting Data Classes

/**
 * 订单信息
 */
@Data
public class Order {
    /** 金额 */
    private int amount;
    /** 支付类型 */
    private String paymentType;
}
/**
 * 支付返回结果类
 */
@Data
@AllArgsConstructor
public class PayResult {
    /** 支付结果 */
    private String result;
}

3. Implement Concrete Strategies

WeChat Pay implementation:

/**
 * 微信支付实现
 */
@Service("WechatPay")
public class WechatPay implements IPayment {
    @Override
    public PayResult pay(Order order) {
        return new PayResult("微信支付成功");
    }
}

Alipay implementation:

/**
 * 支付宝支付
 */
@Service("Alipay")
public class Alipay implements IPayment {
    @Override
    public PayResult pay(Order order) {
        return new PayResult("支付宝支付成功");
    }
}

UnionPay (cloud flash pay) implementation:

/**
 * 银联云闪付
 */
@Service("UnionPay")
public class UnionPay implements IPayment {
    @Override
    public PayResult pay(Order order) {
        return new PayResult("云闪付支付成功");
    }
}

4. Use the Strategy

In a Spring‑based controller we retrieve the appropriate strategy bean by its name (the payment type) and invoke the pay method.

/**
 * 支付服务
 */
@RestController
public class PayController {
    @Autowired
    private ApplicationContext applicationContext;

    @ApiOperation("测试策略模式支付方式选择")
    @RequestMapping("/pay")
    public PayResult pay(@RequestParam("amount") int amount,
                         @RequestParam("paymentType") String paymentType) {
        Order order = new Order();
        order.setAmount(amount);
        order.setPaymentType(paymentType);
        // 根据支付类型获取对应的策略 bean
        IPayment payment = applicationContext.getBean(order.getPaymentType(), IPayment.class);
        // 开始支付
        return payment.pay(order);
    }
}

Testing the endpoint (e.g., http://localhost:8082/pay?amount=8800&paymentType=Alipay) returns the corresponding success message, confirming that different payment strategies are correctly selected at runtime.

Overall, the Strategy pattern provides a clean, extensible way to handle multiple interchangeable behaviors such as payment methods in backend Java applications.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Design PatternsJavaStrategy Patternspringdependency-injectionpayment
Selected Java Interview Questions
Written by

Selected Java Interview Questions

A professional Java tech channel sharing common knowledge to help developers fill gaps. Follow us!

0 followers
Reader feedback

How this landed with the community

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.