Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • System Design Tutorial
  • What is System Design
  • System Design Life Cycle
  • High Level Design HLD
  • Low Level Design LLD
  • Design Patterns
  • UML Diagrams
  • System Design Interview Guide
  • Scalability
  • Databases
Open In App
Next Article:
Iterator Method | JavaScript Design Pattern
Next article icon

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.

State-Method-Design-Pattern

Important Topics for State Design Patterns in JavaScript

  • Key Component of State Design Patterns
  • Example for State Design Patterns in JavaScript
  • Advantages for State Design Patterns
  • Disadvantages for State Design Patterns

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.

Next Article
Iterator Method | JavaScript Design Pattern

P

prakee99db
Improve
Article Tags :
  • Design Pattern
  • Geeks Premier League
  • System Design
  • Geeks Premier League 2023
  • JavaScript Design Patterns

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
    8 min read
  • Creational Software Design Patterns in JavaScript

    • Builder 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 JavaScript

      • Template 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
      geeksforgeeks-footer-logo
      Corporate & Communications Address:
      A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
      Registered Address:
      K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
      GFG App on Play Store GFG App on App Store
      Advertise with us
      • Company
      • About Us
      • Legal
      • Privacy Policy
      • In Media
      • Contact Us
      • Advertise with us
      • GFG Corporate Solution
      • Placement Training Program
      • Languages
      • Python
      • Java
      • C++
      • PHP
      • GoLang
      • SQL
      • R Language
      • Android Tutorial
      • Tutorials Archive
      • DSA
      • Data Structures
      • Algorithms
      • DSA for Beginners
      • Basic DSA Problems
      • DSA Roadmap
      • Top 100 DSA Interview Problems
      • DSA Roadmap by Sandeep Jain
      • All Cheat Sheets
      • Data Science & ML
      • Data Science With Python
      • Data Science For Beginner
      • Machine Learning
      • ML Maths
      • Data Visualisation
      • Pandas
      • NumPy
      • NLP
      • Deep Learning
      • Web Technologies
      • HTML
      • CSS
      • JavaScript
      • TypeScript
      • ReactJS
      • NextJS
      • Bootstrap
      • Web Design
      • Python Tutorial
      • Python Programming Examples
      • Python Projects
      • Python Tkinter
      • Python Web Scraping
      • OpenCV Tutorial
      • Python Interview Question
      • Django
      • Computer Science
      • Operating Systems
      • Computer Network
      • Database Management System
      • Software Engineering
      • Digital Logic Design
      • Engineering Maths
      • Software Development
      • Software Testing
      • DevOps
      • Git
      • Linux
      • AWS
      • Docker
      • Kubernetes
      • Azure
      • GCP
      • DevOps Roadmap
      • System Design
      • High Level Design
      • Low Level Design
      • UML Diagrams
      • Interview Guide
      • Design Patterns
      • OOAD
      • System Design Bootcamp
      • Interview Questions
      • Inteview Preparation
      • Competitive Programming
      • Top DS or Algo for CP
      • Company-Wise Recruitment Process
      • Company-Wise Preparation
      • Aptitude Preparation
      • Puzzles
      • School Subjects
      • Mathematics
      • Physics
      • Chemistry
      • Biology
      • Social Science
      • English Grammar
      • Commerce
      • World GK
      • GeeksforGeeks Videos
      • DSA
      • Python
      • Java
      • C++
      • Web Development
      • Data Science
      • CS Subjects
      @GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
      We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
      Lightbox
      Improvement
      Suggest Changes
      Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
      geeksforgeeks-suggest-icon
      Create Improvement
      Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
      geeksforgeeks-improvement-icon
      Suggest Changes
      min 4 words, max Words Limit:1000

      Thank You!

      Your suggestions are valuable to us.

      What kind of Experience do you want to share?

      Interview Experiences
      Admission Experiences
      Career Journeys
      Work Experiences
      Campus Experiences
      Competitive Exam Experiences