0% found this document useful (0 votes)
14 views5 pages

Design Patterns in C# Part 1 - Unleashing The Power of The Strategy Pattern - by João Melo - Medium

This document introduces the Strategy design pattern in C#, emphasizing its flexibility in choosing algorithms at runtime. It provides a real-world example of implementing the Strategy pattern for payment processing, showcasing how to define a strategy interface and concrete strategies for different payment methods. The article concludes by encouraging readers to apply the Strategy pattern in their projects for improved code maintainability.

Uploaded by

ekrrmerder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views5 pages

Design Patterns in C# Part 1 - Unleashing The Power of The Strategy Pattern - by João Melo - Medium

This document introduces the Strategy design pattern in C#, emphasizing its flexibility in choosing algorithms at runtime. It provides a real-world example of implementing the Strategy pattern for payment processing, showcasing how to define a strategy interface and concrete strategies for different payment methods. The article concludes by encouraging readers to apply the Strategy pattern in their projects for improved code maintainability.

Uploaded by

ekrrmerder
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

19/12/2024, 16:06 Design Patterns in C# Part 1: Unleashing the Power of the Strategy Pattern | by João Melo | Medium

Open in app

Search

Your membership will expire on January 11, 2025 Reactivate membership

Design Patterns in C# Part 1: Unleashing the


Power of the Strategy Pattern
João Melo · Follow
4 min read · May 28, 2024

Listen Share More

Mastering Design Patterns in C#: A Comprehensive Series

Throughout this series, we’ll explore a variety of design patterns to enhance your C#
programming skills. Design patterns are crucial for solving common problems,
improving code structure, and making software more maintainable and scalable.

We’ll cover a wide range of patterns, from creational to behavioral, including


Singleton, Factory Method, Observer, Decorator, and Strategy.
https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-1-unleashing-the-power-of-the-strategy-pattern-82dbb0caf2b9 1/13
19/12/2024, 16:06 Design Patterns in C# Part 1: Unleashing the Power of the Strategy Pattern | by João Melo | Medium

Stay tuned for practical examples and clear explanations to help you master these
design patterns and write cleaner, more efficient code.

Introduction

Hey there, fellow coder! Ever found yourself stuck with a bunch of algorithms to
choose from, and you’re not sure which one to use? Or maybe you’ve hard-coded
your logic, and now it’s a pain to update or swap algorithms? That’s where the
Strategy design pattern comes to the rescue!

In this guide, we’ll break down the Strategy pattern, explain why it’s useful, and
show you how to implement it in C#. Plus, we’ll look at some real-world scenarios
where this pattern can make your life a lot easier.

💡Type — Behavioral patterns are concerned with algorithms and the assignment
of responsibilities between objects. They help manage and organize complex
communications between entities in a system.

What’s the Strategy Design Pattern?

The Strategy design pattern is all about choosing an algorithm at runtime. Instead of
embedding a single algorithm in your code, you define a family of algorithms,
encapsulate each one in a class, and make them interchangeable. This way, you can
change the algorithm without messing with the client code.

Why Use the Strategy Pattern?

The main reason to use the Strategy pattern is flexibility. It lets you define a set of
algorithms, encapsulate them, and switch between them as needed. This makes
your code cleaner and easier to maintain. You can add new algorithms without
touching existing code, which is a big win for keeping things simple and adhering to
the Open/Closed Principle.

Real-world example in C# — Payment Processing

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-1-unleashing-the-power-of-the-strategy-pattern-82dbb0caf2b9 2/13
19/12/2024, 16:06 Design Patterns in C# Part 1: Unleashing the Power of the Strategy Pattern | by João Melo | Medium

Imagine you’re building an e-commerce platform that needs to handle different


payment methods (Credit Card, PayPal, Bitcoin). Using the Strategy pattern, you can
create a PaymentStrategy interface and implement concrete strategies for each
payment method. This way, you can easily switch or add new payment methods
without changing the core payment processing code. Let’s dive into some code to
see how this works in practice.

Step 1: Define the Strategy Interface

Create an interface for your strategies. First, we create the IPaymentStrategy


interface with a single method ProcessPayment.

public interface IPaymentStrategy


{
void ProcessPayment(double amount);
}

Step 2: Implement Concrete Strategies

Create classes that implement this interface, each with a different algorithm. So
next, we implement the strategy interface in three concrete classes:
CreditCardPayment, PayPalPayment, and BitcoinPayment.

public class CreditCardPayment : IPaymentStrategy


{
public void ProcessPayment(double amount)
{
Console.WriteLine($"Processing credit card payment of ${amount}");
}
}

public class PayPalPayment : IPaymentStrategy


{
public void ProcessPayment(double amount)
{
Console.WriteLine($"Processing PayPal payment of ${amount}");
}
}

public class BitcoinPayment : IPaymentStrategy


{

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-1-unleashing-the-power-of-the-strategy-pattern-82dbb0caf2b9 3/13
19/12/2024, 16:06 Design Patterns in C# Part 1: Unleashing the Power of the Strategy Pattern | by João Melo | Medium

public void ProcessPayment(double amount)


{
Console.WriteLine($"Processing Bitcoin payment of ${amount}");
}
}

Step 3: Create the Context Class

The context class holds a reference to a strategy object and provides a method to set
the strategy dynamically and another to execute the strategy.

public class PaymentContext


{
private IPaymentStrategy _paymentStrategy;

// Method to set the strategy at runtime


public void SetPaymentStrategy(IPaymentStrategy paymentStrategy)
{
_paymentStrategy = paymentStrategy;
}

// Method to execute the strategy


public void ProcessPayment(double amount)
{
_paymentStrategy.ProcessPayment(amount);
}
}

Step 4: Use the Context

In the Main method, we create a PaymentContext object, set different strategies


using the SetPaymentStrategy method, and call the ProcessPayment method to run
the current strategy.

class Program
{
static void Main(string[] args)
{
// Creating the payment context
var paymentContext = new PaymentContext();

// Setting and executing CreditCardPayment


https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-1-unleashing-the-power-of-the-strategy-pattern-82dbb0caf2b9 4/13
19/12/2024, 16:06 Design Patterns in C# Part 1: Unleashing the Power of the Strategy Pattern | by João Melo | Medium

paymentContext.SetPaymentStrategy(new CreditCardPayment());
paymentContext.ProcessPayment(100.0);

// Setting and executing PayPalPayment


paymentContext.SetPaymentStrategy(new PayPalPayment());
paymentContext.ProcessPayment(200.0);

// Setting and executing BitcoinPayment


paymentContext.SetPaymentStrategy(new BitcoinPayment());
paymentContext.ProcessPayment(300.0);
}
}

Conclusion

And that’s it! The Strategy design pattern is a fantastic way to manage different
algorithms and keep your code flexible and maintainable. Whether you’re dealing
with payment methods, sorting algorithms, or travel route planning, the Strategy
pattern has got you covered. Try it out in your next project and see how much
smoother your code maintenance becomes.

In the next post of this series, we will cover the Factory Method and explore how it
allows for the creation of objects without specifying their exact class beforehand.

Did you understand the reference?

C Sharp Programming Dotnet Core Design Patterns Strategy Pattern

Design Patterns In Csharp

https://medium.com/@joaopedrosmelo/design-patterns-in-c-part-1-unleashing-the-power-of-the-strategy-pattern-82dbb0caf2b9 5/13

You might also like