Strategy Design Pattern in Ruby

1. Definition

The Strategy Design Pattern defines a family of algorithms, encapsulates each one, and makes them interchangeable. Strategy lets the algorithm vary independently from the clients that use it.

2. Problem Statement

When you have multiple ways to perform an operation and want to switch between them dynamically, hardcoding every variant of the algorithm makes the code difficult to maintain, extend, and scale.

3. Solution

Encapsulate each algorithm (or strategy) into separate classes with a common interface. This makes it easy to interchange algorithms, extend the system with new algorithms, and isolate the algorithm logic from the main application logic.

4. Real-World Use Cases

1. Different compression algorithms (ZIP, RAR, TAR) for a file archiving application.

2. Various payment methods (Credit Card, PayPal, Stripe) for an e-commerce website.

3. Different AI behaviors in a video game.

5. Implementation Steps

1. Define a strategy interface common to all supported algorithms.

2. Implement concrete strategy classes for each algorithm.

3. Create a context class that uses a strategy object to perform an operation.

6. Implementation in Ruby

# Step 1: Strategy Interface
class Strategy
  def execute
    raise NotImplementedError, "#{self.class} has not implemented method '#{__method__}'"
  end
end
# Step 2: Concrete Strategies
class AddStrategy < Strategy
  def execute(a, b)
    a + b
  end
end
class SubtractStrategy < Strategy
  def execute(a, b)
    a - b
  end
end
# Step 3: Context Class
class Context
  attr_accessor :strategy
  def initialize(strategy)
    @strategy = strategy
  end
  def execute_strategy(a, b)
    @strategy.execute(a, b)
  end
end
# Client Code
context = Context.new(AddStrategy.new)
puts context.execute_strategy(5, 3)  # Outputs 8
context.strategy = SubtractStrategy.new
puts context.execute_strategy(5, 3)  # Outputs 2

Output:

8
2

Explanation:

1. Strategy is an abstract class that defines an interface for all concrete strategies.

2. AddStrategy and SubtractStrategy are concrete strategies that implement specific algorithms.

3. Context is a class that uses a strategy object to perform an operation. The strategy object can be changed at runtime to execute different algorithms.

4. In the client code, we first use the AddStrategy to add two numbers, and then we change the strategy to SubtractStrategy to subtract the numbers.

7. When to use?

Use the Strategy Pattern when:

1. You need to choose an algorithm from a family of algorithms dynamically at runtime.

2. You have multiple ways of doing something, and you want to switch between them easily.

3. You want to isolate the algorithm logic from the main application logic.

4. You want to make a class unaware of the specific algorithms it uses.


Comments