Home > Web Front-end > JS Tutorial > JavaScript Design Patterns - Behavioral - State

JavaScript Design Patterns - Behavioral - State

WBOY
Release: 2024-08-16 06:03:33
Original
1099 people have browsed it

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 };
Copy after login

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

The above is the detailed content of JavaScript Design Patterns - Behavioral - State. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template