You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

是否适合用Strategy Pattern处理支付/预订的动态规则逻辑?

Absolutely! The Strategy Pattern is exactly what you need here—it’s tailor-made for scenarios where you want to avoid messy if-else chains while keeping your code flexible for future rule additions. Let’s break this down step by step.

Is the Strategy Pattern a Good Fit?

Yes, 100%—here’s why it aligns perfectly with your requirements:

  • Eliminates conditional chaos: Instead of cluttering your Product and TicketBooking classes with if-else checks for payment types/rules, you encapsulate each payment logic into its own strategy class.
  • Open/Closed Principle compliance: When you need to add new rules (like amount caps, time restrictions) or new payment methods, you just create new strategy classes—no need to modify existing business code.
  • Single Responsibility: Each strategy handles only its own payment rules and processing, while your Product/TicketBooking classes focus on their core jobs (managing stock, handling bookings).
UML Design for Your Scenario

Here’s a clear class diagram outlining the structure:

classDiagram
    class PaymentStrategy {
        <<interface>>
        +canProcess(quantity: int): boolean
        +processPayment(): void
    }

    class CashPaymentStrategy {
        -maxQuantity: int
        +CashPaymentStrategy(maxQuantity: int)
        +canProcess(quantity: int): boolean
        +processPayment(): void
    }

    class PaypalPaymentStrategy {
        +canProcess(quantity: int): boolean
        +processPayment(): void
    }

    class Product {
        -stock: int
        -paymentStrategy: PaymentStrategy
        +setPaymentStrategy(strategy: PaymentStrategy): void
        +purchase(quantity: int): boolean
    }

    class TicketBooking {
        -paymentStrategy: PaymentStrategy
        +setPaymentStrategy(strategy: PaymentStrategy): void
        +bookTickets(quantity: int): boolean
    }

    PaymentStrategy <|-- CashPaymentStrategy
    PaymentStrategy <|-- PaypalPaymentStrategy
    Product *-- PaymentStrategy
    TicketBooking *-- PaymentStrategy

Key Class Breakdown:

  • PaymentStrategy: The core interface defining the contract for all payment methods. It has two methods:
    • canProcess(int quantity): Validates if the payment method allows the requested quantity (or any future rules like amount limits).
    • processPayment(): Executes the actual payment flow.
  • CashPaymentStrategy: Implements the interface with a configurable maxQuantity (set to 2 for both your Product and TicketBooking scenarios). The canProcess method checks if the requested quantity is within the limit.
  • PaypalPaymentStrategy: Implements the interface with no quantity restrictions—canProcess always returns true.
  • Product: Holds stock and a reference to a PaymentStrategy. It uses the strategy to validate and process purchases, without knowing the details of the payment method.
  • TicketBooking: Similar to Product, but focuses on ticket reservations instead of stock management.
Example Code Snippet (Java)

To make this concrete, here’s a simplified implementation:

// Strategy Interface
interface PaymentStrategy {
    boolean canProcess(int quantity);
    void processPayment();
}

// Cash Payment Strategy
class CashPaymentStrategy implements PaymentStrategy {
    private final int maxQuantity;

    public CashPaymentStrategy(int maxQuantity) {
        this.maxQuantity = maxQuantity;
    }

    @Override
    public boolean canProcess(int quantity) {
        return quantity <= maxQuantity;
    }

    @Override
    public void processPayment() {
        System.out.println("Completing cash payment...");
    }
}

// PayPal Payment Strategy
class PaypalPaymentStrategy implements PaymentStrategy {
    @Override
    public boolean canProcess(int quantity) {
        return true; // No quantity limits
    }

    @Override
    public void processPayment() {
        System.out.println("Completing PayPal payment...");
    }
}

// Product Business Class
class Product {
    private int stock;
    private PaymentStrategy paymentStrategy;

    public Product(int initialStock) {
        this.stock = initialStock;
    }

    public void setPaymentStrategy(PaymentStrategy strategy) {
        this.paymentStrategy = strategy;
    }

    public boolean purchase(int quantity) {
        // Check stock first
        if (quantity > stock) {
            System.out.println("Error: Not enough stock available.");
            return false;
        }
        // Validate payment rules via strategy
        if (!paymentStrategy.canProcess(quantity)) {
            System.out.println("Error: Cash payment limited to " + ((CashPaymentStrategy) paymentStrategy).maxQuantity + " items.");
            return false;
        }
        // Process the purchase
        stock -= quantity;
        paymentStrategy.processPayment();
        System.out.println("Success! Purchased " + quantity + " items.");
        return true;
    }
}

// Usage Example
public class Main {
    public static void main(String[] args) {
        Product wirelessHeadphones = new Product(5);

        // Try cash payment for 3 items (exceeds limit)
        wirelessHeadphones.setPaymentStrategy(new CashPaymentStrategy(2));
        wirelessHeadphones.purchase(3); // Fails

        // Switch to PayPal for 3 items
        wirelessHeadphones.setPaymentStrategy(new PaypalPaymentStrategy());
        wirelessHeadphones.purchase(3); // Succeeds
    }
}
Future Extensibility

When you need to add new rules or payment methods:

  • Add a new rule: For example, a "cash payment max amount of $500" rule—create a LimitedCashPaymentStrategy that adds a maxAmount parameter and updates canProcess to check both quantity and amount.
  • Add a new payment method: Implement a CreditCardPaymentStrategy with its own rules (like verification checks) and plug it into Product/TicketBooking via setPaymentStrategy.

No messy if-else changes required—your core business classes stay untouched!

内容的提问来源于stack exchange,提问作者elkaco

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:04:18