Last active
December 30, 2024 12:28
-
-
Save EfeAgare/6f8582637796b9c17ea52cdb72c0ca09 to your computer and use it in GitHub Desktop.
Design-pattern -Strategy--and--Factory--Adapter
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CreditCardPayment | |
def pay(amount) | |
puts "Processing credit card payment of #{amount}" | |
end | |
end | |
class PayPalPayment | |
def pay(amount) | |
puts "Processing PayPal payment of #{amount}" | |
end | |
end | |
------------------------------- | |
# Define Strategies, For Behaviour Design Pattern | |
class PaymentProcessor | |
def initialize(strategy) | |
@strategy = strategy | |
end | |
def process_payment(amount) | |
@strategy.pay(amount) | |
end | |
end | |
# Use different strategies at runtime | |
payment = PaymentProcessor.new(CreditCardPayment.new) | |
payment.process_payment(100) | |
payment = PaymentProcessor.new(PayPalPayment.new) | |
payment.process_payment(200) | |
--------------------------------------------------------------- | |
### Factory design Pattern under Creational Design Pattern | |
class PaymentFactory | |
def self.create(payment_method) | |
case payment_method | |
when :credit_card | |
CreditCardPayment.new | |
when :paypal | |
PayPalPayment.new | |
else | |
raise "Unknown payment method: #{payment_method}" | |
end | |
end | |
end | |
# Use the factory to create instances | |
payment = PaymentFactory.create(:credit_card) | |
payment.pay(100) | |
payment = PaymentFactory.create(:paypal) | |
payment.pay(200) | |
--------------------------- | |
### Adapter pattern For Structural Design Pattern | |
# Existing incompatible APIs | |
class StripeAPI | |
def charge(amount) | |
"Charged $#{amount} using Stripe" | |
end | |
end | |
class PayPalAPI | |
def make_payment(amount) | |
"Paid $#{amount} using PayPal" | |
end | |
end | |
# Adapter | |
class PaymentAdapter | |
def initialize(payment_system) | |
@payment_system = payment_system | |
end | |
def pay(amount) | |
if @payment_system.is_a?(StripeAPI) | |
@payment_system.charge(amount) | |
elsif @payment_system.is_a?(PayPalAPI) | |
@payment_system.make_payment(amount) | |
else | |
raise "Unsupported payment system" | |
end | |
end | |
end | |
# Usage | |
stripe_payment = PaymentAdapter.new(StripeAPI.new) | |
puts stripe_payment.pay(100) # Output: "Charged $100 using Stripe" | |
paypal_payment = PaymentAdapter.new(PayPalAPI.new) | |
puts paypal_payment.pay(200) # Output: "Paid $200 using PayPal" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment