File tree Expand file tree Collapse file tree 5 files changed +77
-0
lines changed
Expand file tree Collapse file tree 5 files changed +77
-0
lines changed Original file line number Diff line number Diff line change 1+ import { VendingMachine } from "./VendingMachine" ;
2+ import { VendingState } from "./VendingState" ;
3+ import { WorkingState } from "./WorkingState" ;
4+
5+
6+ export class IdleState extends VendingState {
7+ public insertCoin ( machine : VendingMachine ) : VendingState {
8+ console . log ( 'Coin inserted, transitioning to WorkingState' ) ;
9+ return new WorkingState ( ) ;
10+ }
11+ public dispense ( machine : VendingMachine ) : void {
12+ console . log ( 'Cannot dispense, no coin inserted' ) ;
13+ }
14+ }
Original file line number Diff line number Diff line change 1+ import { VendingState } from './VendingState' ;
2+
3+ export class VendingMachine {
4+ private state : VendingState ;
5+
6+ constructor ( initialState : VendingState ) {
7+ this . state = initialState ;
8+ }
9+
10+ public setState ( state : VendingState ) : void {
11+ this . state = state ;
12+ }
13+
14+ public insertCoin ( ) : void {
15+ this . state = this . state . insertCoin ( this ) ;
16+ }
17+
18+ public dispense ( ) : void {
19+ this . state . dispense ( this ) ;
20+ }
21+
22+ public getState ( ) : VendingState {
23+ return this . state ;
24+ }
25+ }
Original file line number Diff line number Diff line change 1+ import { VendingMachine } from "./VendingMachine" ;
2+
3+
4+ export abstract class VendingState {
5+ abstract insertCoin ( machine : VendingMachine ) : VendingState ;
6+ abstract dispense ( machine : VendingMachine ) : void ;
7+ }
Original file line number Diff line number Diff line change 1+ import { VendingMachine } from "./VendingMachine" ;
2+ import { VendingState } from "./VendingState" ;
3+
4+
5+ export class WorkingState extends VendingState {
6+ public insertCoin ( machine : VendingMachine ) : VendingState {
7+ console . log ( 'Coin already inserted, cannot insert another' ) ;
8+ return this ;
9+ }
10+ public dispense ( machine : VendingMachine ) : void {
11+ console . log ( 'Dispensing item, transitioning to IdleState' ) ;
12+ }
13+ }
Original file line number Diff line number Diff line change 1+ import { IdleState } from "./IdleState" ;
2+ import { VendingMachine } from "./VendingMachine" ;
3+ import { WorkingState } from "./WorkingState" ;
4+
5+
6+ class StatePattern {
7+ static main ( ) : void {
8+ console . log ( 'State Pattern' ) ;
9+ const vendingMachine = new VendingMachine ( new IdleState ( ) ) ;
10+ const vendingMachine2 = new VendingMachine ( new WorkingState ( ) ) ;
11+ const vendingState1 = vendingMachine . insertCoin ( ) ;
12+ const vendingState2 = vendingMachine2 . insertCoin ( ) ;
13+ vendingMachine . dispense ( ) ;
14+ vendingMachine2 . dispense ( ) ;
15+ }
16+ }
17+
18+ StatePattern . main ( ) ;
You can’t perform that action at this time.
0 commit comments