-
Notifications
You must be signed in to change notification settings - Fork 0
Adapter Design Pattern
Dean Hristov edited this page Sep 18, 2023
·
2 revisions
An Adapter is a structural design pattern that allows objects with incompatible interfaces to collaborate with each other. This design pattern uses inheritance and composition. Usually, the adapter inherits the client code and uses composition to the third-party library. An UML diagram can be found here
- When our service is incompatible with thrid-party piece of code
- Avoid big refactor when switching between DBs (Example MySQL -> MongoDB)
etc...
The client service
export interface IClient {
request(...): void;
}
export default class ClientService implements IClient {
request(...): void {
//TODO Add your business logic here...
}
....
}
The third party service implementation
export interface IThirdPartyService {
specificAction(...): void;
}
export default class ThirdPartyService implements IThirdPartyService {
specificAction(...): void {
// Add your logic here...
}
....
}
The whole magic is happening here - An Adapter class
// Inheriting the client and encapsulate the composition
export default class ClientAdapter extends Client {
private readonly thirdPartyService: ThirdPartyService;
constructor(thirdPartyService: ThirdPartyService) {
super();
this.thirdPartyService = ThirdPartyService;
}
public request(...): number {
return this.externalService.specificAction(...);
}
....
}
More info can be found on the wiki page.