JavaScript Design Patterns - Behavioral - State

nhannguyendevjs

Nhan Nguyen

Posted on August 15, 2024

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:

๐Ÿ’– ๐Ÿ’ช ๐Ÿ™… ๐Ÿšฉ
nhannguyendevjs
Nhan Nguyen

Posted on August 15, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

ยฉ TheLazy.dev

About