Design Patterns In TypeScript — Adapter
How to allow objects with incompatible interfaces to collaborate.
--
Adapter Pattern is a way to organize your code to use a third-party library to compose features of your application. This pattern is also helpful when you want to have a feature abstraction, but you are using a code that you do not have access to or can’t modify.
What is Adapter?
The authors of the book Design Patterns: Elements of Reusable Object-Oriented Software define the Adapter Pattern as:
Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn’t otherwise because of incompatible interfaces.
In other words, the Adapter Design Pattern defines an adapter that implements an interface making calls to classes or libraries that are incompatible with the interface. In that way, we can integrate those classes or libraries following our interfaces.
How To Implement
When we are adopting the Adapter Design Pattern we usually already have the interface created to support features on a module. But sometimes we will define an interface just to implement a new feature, as we will see in the example of this article.
With the interface in hand we will implement its methods on a new Adapter class. This class is responsible for implementing the interface methods by invoking the Adaptee class or the methods of a lib, as we can see in the diagram below.
Then, a client can use the Adaptee features using the Adapter implementation. This way, we can have an Adaptee, which is incompatible with the interface, but will satisfy our interface using the created Adapter. Another benefit of using this pattern is that we can replace a third-party library without changing client code.
Example
In this example, we will use the Adapter Pattern to create a cache module using a Redis client for Node.js called node-redis. This pattern is great for that because it makes enough…