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 Next Article Iterator Method | JavaScript Design Pattern P prakee99db Follow Improve Article Tags : Design Pattern Geeks Premier League System Design Geeks Premier League 2023 JavaScript Design Patterns +1 More Similar Reads JavaScript Design Patterns Tutorial Design patterns in Javascipt are communicating objects and classes that are customized to solve a general design problem in a particular context. Software design patterns are general, reusable solutions to common problems that arise during the design and development of software. They represent best 7 min read Creational Software Design Patterns in JavaScriptBuilder Method | JavaScript Design Pattern The Builder design pattern is a creational design pattern used to construct complex objects by separating the construction process from the actual representation. It's especially useful when an object requires multiple steps or configurations to be created. Important Topics for the Builder Design Pa 9 min read Prototype Method - JavaScript Design Pattern A Prototype Method is a JavaScript design pattern where objects share a common prototype object, which contains shared methods. The prototype method allows you to reuse the properties and methods of the prototype object, and also add new ones as needed. The prototype method is useful for performance 3 min read Abstract Factory Pattern | JavaScript Design Patterns Abstract Factory Pattern is to abstract the process of object creation by defining a family of related factory methods, each responsible for creating a different type of object. These factory methods are organized within an abstract factory interface or class, and the client code uses this interface 6 min read Behavioural Software Design Patterns in JavaScriptTemplate Method | JavaScript Design Patterns Template Method is a behavioral design pattern that defines the skeleton of an algorithm in a base class while allowing subclasses to implement specific steps of the algorithm without changing its structure. It promotes code reusability and provides a way to enforce a consistent algorithm structure 10 min read 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. 4 min read Iterator Method | JavaScript Design Pattern Iterator design pattern is a behavioral design pattern that provides a way to access the elements of an aggregate object sequentially without exposing its underlying representation. It separates the responsibility of accessing and traversing the elements from the aggregate object. This pattern is wi 4 min read Strategy Method | JavaScript Design Pattern Strategy Method or Strategy Pattern in JavaScript helps solve the problem of needing to use different methods or behaviors in your code and easily switch between them. Strategy Method is a behavioral design pattern in JavaScript that defines a family of algorithms, encapsulates each one, and makes t 8 min read Like