banner
Oct 9, 2023
156 Views

Strategy pattern

Written by
banner

Trong lập trình máy tính, mẫu thiết kế chiến lược là một mẫu thiết kế phần mềm hành vi cho phép chọn một thuật toán tại thời điểm chạy thay vì triển khai trực tiếp một thuật toán duy nhất.

In computer programming, the strategy pattern (also known as the policy pattern) is a behavioral software design pattern that enables selecting an algorithm at runtime. Instead of implementing a single algorithm directly, code receives run-time instructions as to which in a family of algorithms to use.

Ví dụ bạn làm phần thanh toán cho website. Khách hàng có thể dùng thẻ, paypal hoặc google wallet để thanh toán

# Define a family of algorithms

class PaymentStrategy:
    def make_payment(self, amount):
        pass

# Implement concrete strategies

class CreditCardPayment(PaymentStrategy):
    def make_payment(self, amount):
        print(f"Paid ${amount} using Credit Card")

class PayPalPayment(PaymentStrategy):
    def make_payment(self, amount):
        print(f"Paid ${amount} using PayPal")

class GoogleWalletPayment(PaymentStrategy):
    def make_payment(self, amount):
        print(f"Paid ${amount} using Google Wallet")

# Context class that uses the strategy

class ShoppingCart:
    def __init__(self, payment_strategy):
        self.cart = []
        self.payment_strategy = payment_strategy

    def add_item(self, item):
        self.cart.append(item)

    def checkout(self):
        total_amount = sum(item['price'] for item in self.cart)
        self.payment_strategy.make_payment(total_amount)

# Usage

if __name__ == "__main__":
    # Create different payment strategies
    credit_card_payment = CreditCardPayment()
    paypal_payment = PayPalPayment()
    google_wallet_payment = GoogleWalletPayment()

    # Create a shopping cart with a payment strategy
    cart1 = ShoppingCart(credit_card_payment)
    cart2 = ShoppingCart(paypal_payment)

    # Add items to the shopping carts
    cart1.add_item({'name': 'Item 1', 'price': 100})
    cart1.add_item({'name': 'Item 2', 'price': 50})
    cart2.add_item({'name': 'Item 3', 'price': 200})

    # Checkout using different payment strategies
    cart1.checkout()  # Paid $150 using Credit Card
    cart2.checkout()  # Paid $200 using PayPal
Article Categories:
dev
banner

Leave a Reply

Your email address will not be published. Required fields are marked *