Context: has a reference to a strategy and invokes it
Calls IStrategy.Method(object);
IStrategy: Defines the interface for the given strategy
Defines the contract Method(object)
Strategy: A concrete implementation of the strategy
Implementation of Method(object)
Select an implementation at runtime based on user input without having to extend the class.
Example: ISalesTaxStrategy is an interface. We have multiple different implementations of Strategies to calculate tax. They all implement the ISalesTaxStrategy interface.
The code below doesn’t need to know what Strategy is chosen at this step. It only needs to invoke the GetTaxFor() Method.
1 2 3 4 5 6
public ISalesTaxStrategy SalesTaxStrategy { get; set; }
switch (origin) { case EnumTaxStrategy.Sweden: salesTaxStrategy = new SwedenSalesTaxStrategy(); break; case EnumTaxStrategy.USA: salesTaxStrategy = new USAStateSalesTaxStrategy(); break; default: salesTaxStrategy = new SwedenSalesTaxStrategy(); break; }
switch (inputInvoiceStrategy) { case EnumInvoiceStrategy.Email: invoiceStrategy = new EmailInvoiceStrategy(); break; case EnumInvoiceStrategy.File: invoiceStrategy = new FileInvoiceStrategy(); break; case EnumInvoiceStrategy.PrintOnDemand: invoiceStrategy = new PrintOnDemandInvoiceStrategy(); break; default: invoiceStrategy = new FileInvoiceStrategy(); break; }
switch (inputShippingStrategy) { case EnumShippingStrategy.DHL: shippingStrategy = new DHLShippingStrategy(); break; case EnumShippingStrategy.Fedex: shippingStrategy = new FedexShippingStrategy(); break; case EnumShippingStrategy.SwedishPostalService: shippingStrategy = new SwedishPostalServiceShippingStrategy(); break; case EnumShippingStrategy.UPS: shippingStrategy = new UPSShippingStrategy(); break; case EnumShippingStrategy.USPS: shippingStrategy = new UnitedStatesPostalServiceShippingStrategy(); break; default: shippingStrategy = new DHLShippingStrategy(); break; }
Summary
One of the most commonly used patterns
Decouple the context and the concrete implementation
Allows for a cleaner implementation in the context
Easily extend with additional startegies without affecting current implementations
Makes testing a lot easier as you can write mocked implementations to inject
Identify existing implementations and where you have used the pattern before
Maybe you could buy me a cup of coffee.
Scan this qrcode
Open alipay app scan this qrcode, buy me a coffee!
Scan this qrcode
Open wechat app scan this qrcode, buy me a coffee!