Created
March 29, 2018 15:19
-
-
Save Dammmien/a1a24b1ff935a8988e09ed8ec97b7286 to your computer and use it in GitHub Desktop.
JavaScript State design pattern
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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