The Strategy Pattern is a behavioral design pattern that enables selecting an algorithm at runtime based on the client's choice. It's a great way to achieve separation of concerns and encapsulate behaviors. Here's an example of how to implement it in C#:
main.cs980 chars44 lines
In this example, CustomerService
is the context that uses the IShippingStrategy
interface to calculate the shipping cost for an order. The USPS
and UPS
classes are the concrete implementations of the IShippingStrategy
interface that encapsulate the algorithms for calculating shipping cost based on the shipping carrier.
By passing in the desired IShippingStrategy
implementation to the CustomerService
constructor, the client can select the algorithm at runtime, rather than hard-coding it in the CustomerService
class. This allows for greater flexibility and ease of maintenance as different shipping carriers can be added or removed without modifying the CustomerService
class.
gistlibby LogSnag