Skip to content

Instantly share code, notes, and snippets.

@Dammmien
Created March 29, 2018 15:19
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Dammmien/a1a24b1ff935a8988e09ed8ec97b7286 to your computer and use it in GitHub Desktop.
Save Dammmien/a1a24b1ff935a8988e09ed8ec97b7286 to your computer and use it in GitHub Desktop.
JavaScript State design pattern
class OrderStatus {
constructor(name, nextStatus) {
this.name = name;
this.nextStatus = nextStatus;
}
doSomething() {
console.log('Do nothing by default');
}
next() {
return new this.nextStatus();
}
}
class WaitingForPayment extends OrderStatus {
constructor() {
super('waitingForPayment', Shipping);
}
doSomething() {
console.log('Do something when order status is "waitingForPayment"');
}
}
class Shipping extends OrderStatus {
constructor() {
super('shipping', Delivered);
}
doSomething() {
console.log('Do something else if order status is "shipping"');
}
}
class Delivered extends OrderStatus {
constructor() {
super('delivered', Delivered);
}
}
class Order {
constructor() {
this.state = new WaitingForPayment();
}
nextState() {
this.state = this.state.next();
};
doSomething() {
return this.state.doSomething();
}
}
const order = new Order();
order.doSomething();
// Do something when order status is "waitingForPayment"
order.nextState();
order.doSomething();
// Do something else if order status is "shipping"
order.nextState();
order.doSomething();
// Do nothing by default
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment