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:
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