"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > JavaScript Design Patterns - Behavioral - State

JavaScript Design Patterns - Behavioral - State

Published on 2024-08-20
Browse:997

JavaScript Design Patterns - Behavioral - State

The state pattern allows an object to alter its behavior when its internal state changes.

In this example, we create a simple state pattern with an Order class that will update the status with the next() method.

const ORDER_STATUS = {
  waitingForPayment: 'Waiting for payment',
  shipping: 'Shipping',
  delivered: 'Delivered',
};

class OrderStatus {
  constructor(name, nextStatus) {
    this.name = name;
    this.nextStatus = nextStatus;
  }

  next() {
    return new this.nextStatus();
  }
}

class WaitingForPayment extends OrderStatus {
  constructor() {
    super(ORDER_STATUS.waitingForPayment, Shipping);
  }
}

class Shipping extends OrderStatus {
  constructor() {
    super(ORDER_STATUS.shipping, Delivered);
  }
}

class Delivered extends OrderStatus {
  constructor() {
    super(ORDER_STATUS.delivered, Delivered);
  }
}

class Order {
  constructor() {
    this.state = new WaitingForPayment();
  }

  next() {
    this.state = this.state.next();
  }
}

export { Order };

A complete example is here ? https://stackblitz.com/edit/vitejs-vite-6zcfql?file=state.js

Conclusion

Use this pattern when the object’s behavior depends on its state, and its behavior changes in runtime depending on that state.


I hope you found it helpful. Thanks for reading. ?

Let's get connected! You can find me on:

  • Medium: https://medium.com/@nhannguyendevjs/
  • Dev: https://dev.to/nhannguyendevjs/
  • Hashnode: https://nhannguyen.hashnode.dev/
  • Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
  • X (formerly Twitter): https://twitter.com/nhannguyendevjs/
  • Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Release Statement This article is reproduced at: https://dev.to/nhannguyendevjs/javascript-design-patterns-behavioral-state-3e9b?1 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3