Maison  >  Article  >  interface Web  >  Modèles de conception JavaScript - Comportementaux - État

Modèles de conception JavaScript - Comportementaux - État

WBOY
WBOYoriginal
2024-08-16 06:03:331068parcourir

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 };

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn