Open In App

State Method Design Patterns in JavaScript

State method or State Design Patterns is a pattern that allows an object to alter its behavior when internal state changes occur. This pattern is used when an object wants to change its state dynamically. When we want to change behavior of object it internally uses if-else block to perform actions.



Key Component of State Design Patterns

Example for State Design Patterns in JavaScript

Problem Statement:



A fan has states like Low Speed, High Speed, Off, Low Speed, Medium Speed.

Stepwise Implementation of State Method

Below is the implementation of the above example problem in JavaScript:




class offFanState{//Fan is in initial state
  constructor(fan){//Creating a constructor
    this.fan=fan;//This variable accessing current class
  }
 
  clickButton(){
    console.log("Keep fan on low speed");//Initial Fan kept on low speed
    this.fan.setState(this.fan.lowSpeedStateOfFan);//Setting fan lo LowSpeedFanState
  }
}
 
class HighSpeedFanState{//Creating class for highspeed
  constructor(fan){
    this.fan=fan;
  }
 
  clickButton(){
    console.log("Switch Off Fan");//Swichting off the fan
    this.fan.setState(this.fan.offFanStateOfFan);//by setting state to above off class using this
  }
}
 
class LowSpeedFanState{//Low speed class
  constructor(fan){
    this.fan = fan;
  }
 
  clickButton(){
    console.log("Switch using state method to Medium speed");
    this.fan.setState(this.fan.mediumSpeedStateOfFan);//by setting state to  medium class using this
  }
}
 
class MediumSpeedFanState{//Medium state class
  constructor(fan){
    this.fan=fan;
  }
 
  clickButton() {
    console.log("Switch using state method to High speed");
    this.fan.setState(this.fan.highSpeedStateOfFan);//by setting state to  highspeed class using this
  }
}
 
class Fan{//Main Class
  constructor(){//Create instances for all states using this
    this.offFanState=new offFanState(this);
    this.highSpeedStateOfFan=new HighSpeedFanState(this);
    this.lowSpeedStateOfFan=new LowSpeedFanState(this);
    this.mediumSpeedStateOfFan=new MediumSpeedFanState(this);
    this.presentState=this.offFanState;
  }
 
  setState(presentState){//Setting presentState
    this.presentState=presentState;
  }
 
  clickButton(){//Creating Button
    this.presentState.clickButton();
  }
}
 
let fanStates=new Fan();
fanStates.clickButton(); //Low speed
fanStates.clickButton(); //Medium speed
fanStates.clickButton(); //High Speed
fanStates.clickButton(); //Switch off fan

Output:

Keep fan on low speed
Switch using state method to Medium speed
Switch using state method to High speed
Switch Off Fan

Diagrammatic Representation of above Example:

It includes:-

Actors:

System:

Use cases:

Advantages for State Design Patterns

Disadvantages for State Design Patterns


Article Tags :