wasAsked.

what is strategy pattern?

Mphasis · Role not specified · technical

Published

Year not specified · Software Engineering

Community answers

Posted by wasAsked editorial collection

The Strategy pattern is a behavioural design pattern that defines a family of algorithms, encapsulates each one in its own class, and makes them interchangeable at runtime. The client depends on a common interface, not on specific implementations. Problem it solves Replacing large if/else or switch statements that select behaviour (shipping cost rules, payment methods, discount types, export formats), which grow every time a new option is added and violate the Open/Closed Principle. Example: shipping cost calculation public interface IShippingStrategy { string Name { get; } decimal Calculate(Order order); } public sealed class StandardShipping : IShippingStrategy { public string Name => "standard"; public decimal Calculate(Order o) => o.Total >= 500 ? 0 : 50; } public sealed class ExpressShipping : IShippingStrategy { public string Name => "express"; public decimal Calculate(Order o) => 120 + o.WeightKg * 10; } public sealed class SameDayShipping : IShippingStrategy { public string Name => "same-day"; public decimal Calculate(Order o) => 250; } // Context that uses a strategy public sealed class ShippingCalculator(IEnumerable<IShippingStrategy> strategies) { private readonly Dictionary<string, IShippingStrategy> _byName = strategies.ToDictionary(s => s.Name); public decimal Calculate(Order order, string method) => _byName.TryGetValue(method, out var strategy) ? strategy.Calculate(order) : throw new ArgumentException($"Unknown shipping method '{method}'."); } // Registration with dependency injection builder.Services.AddSingleton<IShippingStrategy, StandardShipping>(); builder.Services.AddSingleton<IShippingStrategy, ExpressShipping>(); builder.Services.AddSingleton<IShippingStrategy, SameDayShipping>(); builder.Services.AddSingleton<ShippingCalculator>(); Adding a new shipping method means adding one class and one registration — no changes to ShippingCalculator. (.NET 8 keyed services are another way to select a strategy: [FromKeyedServices("express")].) Benefits - Open/Closed: extend behaviour without modifying existing code. - Each algorithm is isolated, small and independently unit-testable. - Behaviour can be selected at runtime (user choice, configuration, A/B tests). Drawbacks - More classes; for two simple options, an if statement may be clearer. - Clients or a factory must know how to choose the right strategy. Related patterns: Factory (often used to pick the strategy), State (similar structure but the object changes behaviour based on internal state), and Template Method (inheritance-based variation). In simple cases a Func<Order, decimal> delegate can act as a lightweight strategy.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics