DI Payment Provider Swap

CSharp · Console

/Program.cs

using System;
using System.Globalization;

public interface IPayment
{
    void ApplyPayment(decimal amount);
}

public class GooglePayment : IPayment
{
    public void ApplyPayment(decimal amount) =>
        Console.WriteLine($"Processing {amount:C} through Google Pay...");
}

public class StripePayment : IPayment
{
    public void ApplyPayment(decimal amount) =>
        Console.WriteLine($"Processing {amount:C} through Stripe...");
}

public class CheckoutService
{
    private readonly IPayment _payment;

    public CheckoutService(IPayment payment)
    {
        _payment = payment;
    }

    public void Checkout(decimal amount) => _payment.ApplyPayment(amount);
}

public class Program
{
    public static void Main()
    {
        CultureInfo.CurrentCulture = new CultureInfo("en-US");

        // Try changing GooglePayment to StripePayment below and hit Run again.
        // CheckoutService never has to change.
        IPayment payment = new GooglePayment();

        var checkout = new CheckoutService(payment);
        checkout.Checkout(49.99m);
    }
}
;