The Adapter Design Pattern is a structural design pattern. This design pattern acts as a bridge between two different interfaces. It can convert the interface of a class, to make it compatible with a client who is expecting a different interface, without changing the source code of the class.
The adapter pattern should be used when:
Interface for each adapter:
interface IPayment { pay(): void; }
Concrete implement of ApplePay & ApplePayAdapter class
export class ApplePay { checkout() { return `${this.startTransaction()} - ${this.transfer()} - ${this.completedTransaction()}`; } private startTransaction() { return 'Apple pay start transaction'; } private transfer() { return 'Apple pay is transferring'; } private completedTransaction() { return 'Apple pay transaction completed'; } } export class ApplePayAdapter implements IPayment { private readonly _applePay: ApplePay; constructor() { this._applePay = new ApplePay(); } pay() { return this._applePay.checkout(); } }
Concrete implement of StripePay & StripePayAdapter class
export class StripePay { private readonly _money: number; constructor(money: number) { this._money = money; } charge() { return `Stripe pay charge: ${this._money}$`; } } export class StripePayAdapter implements IPayment { private readonly _stripePay: StripePay; constructor(money: number) { this._stripePay = new StripePay(money); } pay() { return this._stripePay.charge(); } }
The client code:
function client() { const stripe = new StripePayAdapter(150); const apple = new ApplePayAdapter(); console.log(stripe.pay()); console.log(apple.pay()); } client();
Result:
Stripe pay charge: 150$ Apple pay start transaction - Apple pay is transferring - Apple pay transaction completed
Pros:
Cons:
Thank you for reading, and happy coding!
I hope this article will help make the concepts of the Adapter Pattern