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
Top comments (0)