Challenge: Solution Review
This lesson will explain the solution to the problem from the last coding challenge.
Solution #
Explanation #
Let’s start by looking at the code we had originally:
As you can see, there is a parent class Applications. It has four child classes:
-
FacebookLightMode -
FacebookDarkMode -
WhatsAppLightMode -
WhatsAppDarkMode
The definitions of these classes are simple. Apart from initializing the application name and type, each class also defines the following functions:
-
display -
displayMode
Each class has its definition of both these functions. display shows the type of application, and displayMode shows the mode.
So why should we apply the bridge pattern? In the code above, we had to make a different class for each mode, dark and light. Now imagine doing this for 1000 other applications. It would be better to have a separate interface for the modes of application. Here’s what we want to do:
Let’s check out its coding implementation so you can see the improvement in the code.
We start by creating a Mode class.
class Mode{
constructor(app){
this.app = app
this.lightMode = function(){
this.app.setLightMode()
}
this.darkMode = function(){
this.app.setDarkMode()
}
}
}
You can pass an app object to this class and call the lightMode and darkMode on it. lightMode takes the app and calls the setLightMode function on it. darkModetakes the app and calls the setDarkMode function on it.
In our example, we are considering two applications whose modes we can set: Facebook and Whatsapp. Previously, we had two classes for each, one for dark mode and one for light mode. Since the Mode class is available to set the mode, we don’t need the separate classes.
In the modified version, we have a single Facebook and Whatsapp class.
class Facebook extends Applications{
//code...
}
class WhatsApp extends Applications{
//code...
}
These classes initialize a mode variable in their constructors. By default, the mode of the app is set to light.
class Facebook extends Applications{
//code...
this.mode = "light"
}
class WhatsApp extends Applications{
//code...
this.mode = "light"
}
Both apps contain additional methods:
-
setLightModethis.setLightMode = function(){ this.mode = "light" }Sets the
modetolight. -
setDarkModethis.setDarkMode = function(){ this.mode = "dark" }Sets the
modetodark.
When an app calls these methods, the mode of the app is set accordingly.
The display method is the same as before. The displayMode method has a minute modification:
displayMode(){
console.log(`You are using whatsapp in ${this.mode} mode.`)
}
Instead of explicitly writing dark mode or light mode in the message as before, we use ${this.mode} to display the mode.
Now, setting the mode of an app is simple. We create an application, pass it to the Mode class, and call the required mode on it.
const fb = new Facebook("Facebook", "Social Networking")
const mode = new Mode(fb)
mode.darkMode()
Let’s discuss the composite pattern in the next lesson.