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.
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.
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.
So, how I can use my
Book
in
Shop
even if Shop class communicates only with
Item
? 🤔
Adapter pattern to the rescue
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).
Now we're ready to test our program in
index.ts
class.
And run the app
Let's add another class for movies that'll have different behaviors then the
Book
class.
And create
MovieAdapter
that'll act as an adapter between Item and Movie.
We can add our movies in main class and test it.
After adding movies to our shopStat
(shopStat.add(movie1);
shopStat.add(movie2);
) we can run the app again
And everything works fine 👍 I hope this text was helpful for understanding this useful pattern.