Understanding Adapter Design Pattern

Introduction

In this article, we will cover the Adapter Design Pattern.

What is an Adapter?

Adapter Design Pattern acts as a bridge between incompatible interfaces, allowing them to work together seamlessly. It converts the interface of a class into another interface that a client expects.

Why User Adapter?

In real-world scenarios, systems evolve independently, leading to incompatible interfaces between components. Adapter Pattern helps integrate such components without modifying their existing code, thus promoting reusability and flexibility.

Where to Use Adapter?

Adapter Pattern is ideal when integrating legacy systems with modern ones, incorporating third-party libraries, or working with diverse APIs. It's invaluable in scenarios where interface mismatches hinder interoperability.

How to Implement?

To implement the Adapter Pattern, create an adapter class that implements the target interface and wraps an instance of the adaptee class. The adapter class maps calls from the target interface to the adaptee's interface.

Example. Payment Gateway Integration

let's consider a scenario where a client's e-commerce platform needs to integrate various payment gateways to process transactions. One such gateway is GooglePay, which has a unique interface.

public interface IPaymentGateway 
 {
   void ProcessPayment(double amount); 
 }
  
// Adaptee - GooglePay getway with its unique interface 
public class GooglePayService 
 {
   public void MakePayment(double amount) 
   {
     Console.WriteLine($"GooglePay payment of {amount} processed successfully.");
   }
 }
// Adapter for GooglePayService 
public class GooglePayAdapter : IPaymentGateway 
 {
   private readonly GooglePayService _googlePayService;
   
   public GooglePayAdapter(GooglePayService googlePayService) 
   {
    _googlePayService = googlePayService ?? throw new ArgumentNullException(nameof(googlePayService));
   }
    
   public void ProcessPayment(double amount) 
   {
     _googlePayService.MakePayment(amount); 
   }
}
// client code
public class PaymentProcessor 
{
  public void ProcessPayment(IPaymentGateway paymentGateway, double amount) 
  {
     paymentGateway.ProcessPayment(amount);  
  }
} 
public class Program
 {
	public static void Main(string[] args)
	 {
		var processor = new PaymentProcessor();
		
        // Integrating GooglePay payment getway using Adapter
		var googlePayService = new GooglePayService();
		IPaymentGateway googlePayAdapter = new GooglePayAdapter(googlePayService);
		processor.ProcessPayment(googlePayAdapter, 5000);
	}
}

Output

Note. Similar integration can be done for other payment gateways using adapters.


Similar Articles