You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
kubsu-sm5-ruby/strategy_pattern.rb

49 lines
1.4 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# Интерфейс стратегии (общий для всех стратегий)
class PaymentStrategy
def pay(amount)
raise NotImplementedError, "Метод pay должен быть реализован в подклассе"
end
end
# Реализация стратегии оплаты картой
class CreditCardPayment < PaymentStrategy
def pay(amount)
puts "Оплата #{amount}с использованием кредитной карты 💳"
end
end
# Реализация стратегии оплаты через SberBank
class SberPayment < PaymentStrategy
def pay(amount)
puts "Оплата #{amount}₽ через Sber ID 🏦"
end
end
# Реализация стратегии оплаты биткоинами
class BitcoinPayment < PaymentStrategy
def pay(amount)
puts "Оплата #{amount}₽ в биткоинах ₿"
end
end
# Контекст использующий стратегию
class PaymentProcessor
def initialize(strategy)
@strategy = strategy
end
def process_payment(amount)
@strategy.pay(amount)
end
end
# === Пример использования ===
card_payment = PaymentProcessor.new(CreditCardPayment.new)
card_payment.process_payment(1000)
paypal_payment = PaymentProcessor.new(SberPayment.new)
paypal_payment.process_payment(2000)
bitcoin_payment = PaymentProcessor.new(BitcoinPayment.new)
bitcoin_payment.process_payment(3000)