Adapter design pattern in TypeScript

Easiest way to understand adapter design pattern is to go through specific problem, and try to solve that same problem with it. Let's say that we have Shop class that looks as shown in the picture below.

01.PNG

Shop class have methods for adding and removing items, methods that return total size and price for items, and one method that describes necessary information. As we can see our Shop class's methods handle only specific Item object type and communicate with Item object's methods which are declared in abstract Item class.

02.PNG

Okay, let's say that I have book.ts class that represents the objects that I want to handle in shop.ts class. And, as you can see in picture below, Book is different than the Item, it has different properties and methods.

03.PNG

So, how I can use my Book in Shop even if Shop class communicates only with Item ? 🤔

Adapter pattern to the rescue

07.PNG

We need to create adapter that will adapt Book to Item , because Book or Shop doesn't need to know each other. As we concluded, our Shop class communicate with Item.
To accomplish that, we'll create adapter class and call it BookAdapter. Our BookAdapter will be an Item (is a relationship) and it will have Book (has a relationship). We'll achieve first relationship by inheritance and second by composition (we'll create instance of a Book class).

08.PNG

Now we're ready to test our program in index.ts class.

10.PNG

And run the app

09.PNG

Let's add another class for movies that'll have different behaviors then the Book class.

11.PNG

And create MovieAdapter that'll act as an adapter between Item and Movie.

12.PNG

We can add our movies in main class and test it.

13.PNG

After adding movies to our shopStat (shopStat.add(movie1); shopStat.add(movie2); ) we can run the app again

14.PNG

And everything works fine 👍 I hope this text was helpful for understanding this useful pattern.