Rails Insights

Using the Strategy Design Pattern in Ruby

Introduction

The Strategy Design Pattern is a behavioral design pattern that allows you to define a family of algorithms, encapsulate each one, and make them interchangeable. This pattern lets the algorithm vary independently from clients that use it.

When to Use the Strategy Design Pattern

The Strategy Design Pattern is useful when you have a set of related algorithms and you need to choose one of them at runtime. It also helps in cases where you have a class that has multiple behaviors and these behaviors need to be represented as classes.

Implementation in Ruby

In Ruby, we can implement the Strategy Design Pattern using a combination of classes and modules. Let's look at an example to understand how this pattern can be used in Ruby.

Example

class PaymentContext
  attr_accessor :strategy

  def initialize(strategy)
    @strategy = strategy
  end

  def execute_payment(amount)
    @strategy.pay(amount)
  end
end

module PaymentStrategy
  class CreditCard
    def pay(amount)
      puts "Paying #{amount} using Credit Card"
    end
  end

  class PayPal
    def pay(amount)
      puts "Paying #{amount} using PayPal"
    end
  end
end

# Client code
payment_context = PaymentContext.new(PaymentStrategy::CreditCard.new)
payment_context.execute_payment(100)

payment_context.strategy = PaymentStrategy::PayPal.new
payment_context.execute_payment(50)

Explanation

In the example above, we have a PaymentContext class that takes a payment strategy as a parameter in its constructor. The execute_payment method of the PaymentContext class delegates the payment to the strategy object.

We have defined two payment strategies - CreditCard and PayPal - as classes inside the PaymentStrategy module. Each payment strategy has a pay method that specifies how the payment should be made.

When the client code creates a PaymentContext object with a specific payment strategy and calls the execute_payment method, the payment is made using the chosen strategy.

Benefits of Using the Strategy Design Pattern

  • Allows for easy swapping of algorithms at runtime
  • Encapsulates algorithms and makes them reusable
  • Improves code maintainability and readability

Conclusion

The Strategy Design Pattern is a powerful tool in Ruby that allows you to encapsulate algorithms and make them interchangeable. By using this pattern, you can easily switch between different algorithms at runtime and improve the flexibility and maintainability of your code.

Published: May 31, 2024

© 2024 RailsInsights. All rights reserved.