DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

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 };
Enter fullscreen mode Exit fullscreen mode

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:

Speedy emails, satisfied customers

Postmark Image

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay