Design Patterns - Strategy
Posted: December 14, 2024

Design Patterns - Strategy
Other Posts in this Series
- Introduction
- Decorator
- Strategy
Introduction
The Strategy pattern is probably one of the most used patterns seen in code bases; the idea of encapsulating functionality in an object and passing that object around goes to the heart of object oriented programming. The Strategy Pattern is one of the Behavioural patterns detailed in the original (Gang of Four book)[https://www.amazon.co.uk/Design-patterns-elements-reusable-object-oriented/dp/0201633612/] and it's specific use is when we have specific algorithms for a specific task, and the client gets to choose at runtime which algorithm is exectuted.
Example
The example we'll use in this case is an eCommerce store that needs to ship physical items to its customers. These customers could be local, national or international and as such might come and collect their purchase in person, might be shipped nationally through a domestic courier, or might be shipped internationally. We don't want our order process to be concerned so we'll use a factory method to determine which shipping method to use, then we'll dispatch the order to that.
Potential Implementation
[INSERT DIAGRAM HERE]
public class OrderClient(IShippingMethodFactory shippingMethodFactory)
{
public Order FinaliseOrder(OrderItems items, Customer customer, Address address)
{
var order = new Order(customer);
order.AddItems(items);
var shippingMethod = shippingMethodFactory.GetShipmentMethodFor(address);
order.SetShippingMethod(shippingMethod);
return order;
}
}
public interface IShippingMethod
{
}