Design Patterns: Strategy with TDD on C#

Onur Vatan
2 min readJan 8, 2021
Photo by Denys Nevozhai on Unsplash

When we have several ways to go to target by circumstances we need to determine a strategy. These days we have a lot of ways to make payments. There are a lot of finance companies that have their own payment systems. And there are a lot of banks that also have their own pos systems. As a software developer, we need to offer all payment ways to our company customers. Strategy pattern is in behavioral pattern group so, that means is changing our behavior by circumstances.

Let’s look at how we can do that with the Strategy pattern?

Let’s start writing test methods with XUnit.

The scenario is there is two way to make payments. They are PayPal and any local bank. Paypal has a 2% commission and the local bank has a 1% commission. But we need just one payment method to charge money and we will need a loosely coupled method when we need to add new payment ways. And also we have to avoid blocks of if statements on our codes. The strategy pattern is helping us to fix that problem.

I have written those test codes below. There is a PaymentClient for whole payments and we inject our PaypalPaymentService for calculating %2 commission and add to the total amount when we make a payment from Paypal. The other one is for a Local bank with a %1 commission.

We need to make our Test successful. We need an interface for commission calculation and also we need a payment method. There are PayPalPaymentService and LocalBankPaymentService classes that inherit from IPaymentService.

After that, we need a PaymentClient for consuming those services.

All tests have passed.

Lastly, let’s look at how we consume PaymentClient with different strategies.

Conclusion

Strategy pattern provides to add any new IPaymentService method to our Payment Client easily. We just need to create a new Service class for a new vendor. Of course, we can improve that code with Dependency injection but I’d like to write and show how we can use strategy pattern.

Thanks for reading 🎉

--

--