Open In App

State Method Design Patterns in JavaScript

Last Updated : 17 Jan, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

State-Method-Design-Pattern

Key Component of State Design Patterns

  • Context: Based on internal State Context object behavior changes. Context refers to the current state object.
  • State:The state is a base class or an interface that defines a set of methods.Each state class implements these methods to provide particular behavior associated with that state.
  • Concrete States:Concrete state class provides the behavior associated with that particular state.Each state provides its own implementation defined by the state interface of its own state methods.

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

  • Identify States:Identifying different states. In this case states include Off, Low Speed, Medium Speed, High Speed.
  • Create State Classes:Create a class for each state. In this case offFanState, HighSpeedFanState, LowSpeedFanState and MediumSpeedFanState.
  • Context Class:Create a context class holding an instance variable that represents current state. Fan represents Context Class and current state is Present State.
  • Define Methods in State Classes:Define methods in every state class. In this case clickButton Method represents the work/action done.
  • Context State Transition Method:In given Context class define methods to set present state. In this case Fan represents Context class and we set it using setState method.
  • Context Delegation: The methods in context class delegates the behavior to present state.
  • Creating Instances:Instantiating the context class and every state class. Setting initial state(this.presentState=this.offFanState).
  • Testing Implementation:We use fanStates.clickButton() for stimulating different state methods.

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

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:

  • User:-User can turn-on, low the speed of fan, medium the speed of fan, high the speed of fan and turn-off the fan.
  • State-Methods:-Includes Low, Medium and High speed of fan changing when user changes.

System:

  • Fan Controller System:-It consists of actors(users, state-methods) and contains use cases like Turn-off, Low-speed, Medium-speed, High-speed and Turn-On.

Use cases:

  • Turn-on Fan:-User initially Turn-on fan.
  • Low-speed:-User lows down the speed of fan. The state changes from OffState to LowSpeedState.
  • Medium-speed:-User increases the speed of fan. The state changes from LowSpeedState to MediumSpeedState.
  • High-speed:-User increases the speed of fan. The state changes from MediumSpeedState to HighSpeedState.
  • Turn-off:-User turns-off the fan. It reaches final state.
    state-method-in-javascript

Advantages for State Design Patterns

  • Clean Code:The state pattern facilitates code pattern and organization. This fosters code cleanliness and enhances maintainability to provide best Output.
  • Flexibility:The State Method makes it easier to add states without affecting the behavior of other states. When there are changes in requirements it is flexible.
  • Readability:Code is more readable as the logic associated with each state is isolated in its own class. This makes it easier for developers to understand.
  • Scalability:Adding new states is easier because each state is encapsulated in its own class. This makes the code more scalable.
  • Encapsulation:Each state is encapsulated in its own class. This reduces complexity of the system.
  • Reusability:States can be reused by different objects. This helps in code reusability.

Disadvantages for State Design Patterns

  • More Number Of States: In case of many states code becomes complex.
  • Learning Curve and Understandability:People who are not familiar with the State pattern and methods might find it difficult to understand the concept of state transitions and machines.
  • Overheads: There might be a slight performance overhead associated with state transitions and the deputation of behavior to different state methods and classes.
  • Applicability: Some situations where the state changes are minimal/less, using the State pattern might be an overkill.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads