Adapter Design Pattern in .NET
The Adapter pattern converts the interface of a class into another interface the client expects. It allows incompatible interfaces to work together without modifying existing code.
Purpose
To enable integration
between systems or components with mismatched interfaces by translating one
interface to another.
Key Characteristics
- Acts as a bridge
between incompatible interfaces
- Promotes reusability
of existing components
- Often used
when integrating third-party services
Pros
- Supports
integration with legacy or external systems
- Avoids
rewriting existing code
- Promotes
flexibility and modularity
Cons
- Adds an
extra layer of abstraction
- Overuse can
lead to complex system dependencies
Use Cases
- Adapting a third-party
payment gateway into a common interface
- Converting external
logging systems to your internal logger
- Integrating legacy
financial APIs into modern interfaces
Real-Time Finance Example: Adapting a
Third-Party Payment Gateway
Suppose your app
expects a common IPaymentProcessor interface, but a third-party provider (e.g.,
RazorPay) exposes a different interface. You can use an Adapter to plug it into
your system.
1. Expected Target Interface
public interface IPaymentProcessor
{
void
Pay(decimal amount);
}
2. Existing Third-Party Class (Incompatible
Interface)
public class RazorPayGateway
{
public void MakePayment(decimal value)
{
Console.WriteLine($"Payment of ₹{value} processed via
RazorPay.");
}
}
3. Adapter Implementation
public class RazorPayAdapter :
IPaymentProcessor
{
private readonly RazorPayGateway _razorPay;
public RazorPayAdapter(RazorPayGateway razorPay)
{
_razorPay = razorPay;
}
public void Pay(decimal amount)
{
_razorPay.MakePayment(amount);
// adapting call
}
}
4. Client Code Usage
class Program
{
static void Main()
{
RazorPayGateway thirdParty = new RazorPayGateway();
IPaymentProcessor paymentProcessor = new RazorPayAdapter(thirdParty);
paymentProcessor.Pay(999.99m);
}
}
Output
Payment of ₹999.99 processed via RazorPay.
Summary
- Adapter
Pattern is
essential for integrating third-party or legacy systems
- Helps
maintain a clean, consistent interface in your application
- Perfect for finance
applications dealing with different APIs or services (payment,
logging, tax, etc.)
Comments
Post a Comment