State Method Design Patterns in JavaScript Last Updated : 17 Jan, 2024 Comments Improve Suggest changes Like Article Like 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. Important Topics for State Design Patterns in JavaScript Key Component of State Design PatternsExample for State Design Patterns in JavaScriptAdvantages for State Design PatternsDisadvantages for State Design PatternsKey Component of State Design PatternsContext: 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 JavaScriptProblem Statement: A fan has states like Low Speed, High Speed, Off, Low Speed, Medium Speed. Stepwise Implementation of State MethodIdentify 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 speedSwitch using state method to Medium speedSwitch using state method to High speedSwitch 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. Advantages for State Design PatternsClean 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 PatternsMore 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. Comment More infoAdvertise with us P prakee99db Follow Improve Article Tags : Design Pattern Geeks Premier League System Design Geeks Premier League 2023 JavaScript Design Patterns +1 More Explore What is System DesignSystem Design Introduction - LLD & HLD7 min readSystem Design Life Cycle | SDLC (Design)7 min readWhat are the components of System Design?10 min readGoals and Objectives of System Design5 min readWhy is it Important to Learn System Design?6 min readImportant Key Concepts and Terminologies â Learn System Design9 min readAdvantages of System Design4 min readSystem Design FundamentalsAnalysis of Monolithic and Distributed Systems - Learn System Design10 min readWhat is Requirements Gathering Process in System Design?7 min readDifferences between System Analysis and System Design4 min readHorizontal and Vertical Scaling | System Design5 min readCapacity Estimation in Systems Design10 min readHow to Answer a System Design Interview Problem/Question?5 min readFunctional and Non Functional Requirements6 min readWeb Server, Proxies and their role in Designing Systems9 min readScalability in System DesignWhat is Scalability and How to achieve it?7 min readWhich Scalability approach is right for our Application? - System Design4 min readPrimary Bottlenecks that Hurt the Scalability of an Application - System Design4 min readDatabases in Designing SystemsComplete Guide to Database Design - System Design11 min readSQL vs. NoSQL - Which Database to Choose in System Design?5 min readFile and Database Storage Systems in System Design4 min readBlock, Object, and File Storage in System Design5 min readDatabase Sharding - System Design8 min readDatabase Replication in System Design6 min readHigh Level Design(HLD)What is High Level Design? - Learn System Design9 min readAvailability in System Design5 min readConsistency in System Design8 min readReliability in System Design5 min readCAP Theorem in System Design5 min readWhat is API Gateway?8 min readWhat is Content Delivery Network(CDN) in System Design7 min readWhat is Load Balancer & How Load Balancing works?8 min readCaching - System Design Concept9 min readCommunication Protocols in System Design6 min readActivity Diagrams - Unified Modeling Language (UML)10 min readMessage Queues - System Design8 min readLow Level Design(LLD)What is Low Level Design or LLD?6 min readAuthentication vs Authorization in LLD - System Design3 min readPerformance Optimization Techniques for System Design3 min readObject-Oriented Analysis and Design(OOAD)6 min readData Structures and Algorithms for System Design6 min readContainerization Architecture in System Design10 min readModularity and Interfaces In System Design8 min readUnified Modeling Language (UML) Diagrams8 min readData Partitioning Techniques in System Design9 min readHow to Prepare for Low-Level Design Interviews?4 min readEssential Security Measures in System Design8 min readDesign PatternsDesign Patterns Tutorial9 min readCreational Design Patterns4 min readStructural Design Patterns7 min readBehavioral Design Patterns5 min readDesign Patterns Cheat Sheet - When to Use Which Design Pattern?7 min readInterview Guide for System DesignHow to Crack System Design Interview Round?9 min readSystem Design Interview Questions and Answers [2025]7 min read5 Common System Design Concepts for Interview Preparation12 min read5 Tips to Crack Low-Level System Design Interviews6 min readSystem Design Interview Questions & AnswersMost Commonly Asked System Design Interview Problems/Questions1 min readDesign Dropbox - A System Design Interview Question14 min readDesigning Twitter - A System Design Interview Question15+ min readSystem Design Netflix | A Complete Architecture15+ min readSystem Design of Uber App | Uber System Architecture14 min readDesign BookMyShow - A System Design Interview Question11 min readDesigning Facebook Messenger | System Design Interview9 min readComplete Roadmap to Learn System Design for Beginners6 min readGuide to System Design for Freshers15+ min readHow Disney+ Hotstar Managed (5 Cr)+ Live Viewers During India's T20 World Cup Win[2024]8 min read Like