Design Patterns in Javascript — Part 2
In this post we will dive into Structural Design Patterns
In the last post we saw the creational patterns. If you missed out on that here is the link : Creational Patterns
Adapter Pattern
Intent: Convert the interface of a class into something different that another client expects. It allows classes to work together that couldn’t otherwise because of the incompatible interfaces.
Say we have a kayak shop. Its been a long time since we updated our system and now we are required to add few more parameters before calculating the rental price of our kayaks. We introduce an adapter so that the client program can still continue to work without changing the API.
Proxy Pattern
Intent: Provide a surrogate or placeholder for another object to control access to it.
Our Bots company from the last post has become huge. It has become very difficult for the manager bot to work without an assistant. lets bring him his assistant called Fiona which will act as a proxy for our manager bot.
Get Akshar Takle’s stories in your inbox
Join Medium for free to get updates from this writer.
Fiona only accepts authenticated requests and also stores her own database of reports for quick retrieval. Lets see how Fiona works
So whenever anyone needs any report from the manager bot, they can simply ask Fiona for it like this
Composite Pattern
Intent: Composites work with trees. Composing objects into tree structures to represent hierarchies. Composites lets clients treat individual object and composition of objects uniformly.
So our bots company has a website and we need to put out our team of bots. We need to show developers testers or any other kind of bots. Lets see how we can use the composites pattern to create the team page of our company.
First we group our bots according to their role and finally form one whole group of employees. We just call print on this one group to create our team page. Here is the output:
Decorator Pattern
Intent: Extend the functionality of an existing objects by dynamically attaching properties and methods.
Sometimes we already have the base objects that we need. For example, lets say we want to upgrade our bots to the newest generation. We could add this functionality by extending the existing bots. Lest see how:
Here we have our first generation bot named Alex. We can use the same bot to create 2nd and 3rd generation Alex with improved relax time.
Thats it! Thank you for reading. If you liked it please give some claps!!
