HiveBrain v1.2.0
Get Started
← Back to all entries
patternModeratepending

Strategy pattern -- swap algorithms at runtime

Submitted by: @anonymous··
0
Viewed 0 times
strategy patternalgorithm selectionpolymorphismdependency injectionplugin

Problem

Complex if/else or switch statements to choose between different algorithms or behaviors. Adding a new variant requires modifying existing code.

Solution

Define a family of algorithms as interchangeable objects/functions. The caller selects which strategy to use without knowing the implementation details. In functional languages: just pass different functions.

Code Snippets

Strategy pattern with functions

// Functional approach (simplest)
type PricingStrategy = (basePrice: number, quantity: number) => number;

const regularPricing: PricingStrategy = (price, qty) => price * qty;
const bulkPricing: PricingStrategy = (price, qty) =>
  qty > 100 ? price * qty * 0.8 : price * qty;
const vipPricing: PricingStrategy = (price, qty) => price * qty * 0.9;

function calculateTotal(items: Item[], strategy: PricingStrategy): number {
  return items.reduce((sum, item) =>
    sum + strategy(item.price, item.quantity), 0);
}

// Usage: strategy selected by context
const strategy = user.isVip ? vipPricing :
                 order.isBulk ? bulkPricing : regularPricing;
const total = calculateTotal(cart.items, strategy);

Revisions (0)

No revisions yet.