File tree 1 file changed +70
-0
lines changed
1 file changed +70
-0
lines changed Original file line number Diff line number Diff line change
1
+ export interface State {
2
+ render ( ) : void ;
3
+ publish ( ) : void ;
4
+ }
5
+
6
+ class Document {
7
+ private state : State ;
8
+
9
+ constructor ( ) {
10
+ this . state = new DraftState ( this ) ;
11
+ }
12
+
13
+ changeState ( state : State ) {
14
+ this . state = state ;
15
+ }
16
+
17
+ render ( ) {
18
+ this . state . render ( ) ;
19
+ }
20
+
21
+ publish ( ) {
22
+ this . state . publish ( ) ;
23
+ }
24
+ }
25
+
26
+ class DraftState implements State {
27
+ constructor ( private document : Document ) { }
28
+
29
+ render ( ) {
30
+ console . log ( "Rendering the document in Draft state" ) ;
31
+ }
32
+
33
+ publish ( ) {
34
+ console . log ( "Moving the document to Moderation state" ) ;
35
+ this . document . changeState ( new ModerationState ( this . document ) ) ;
36
+ }
37
+ }
38
+
39
+ class ModerationState implements State {
40
+ constructor ( private document : Document ) { }
41
+
42
+ render ( ) {
43
+ console . log ( "Rendering the document in Moderation state" ) ;
44
+ }
45
+
46
+ publish ( ) {
47
+ console . log ( "Making the document public in Published state" ) ;
48
+ this . document . changeState ( new PublishedState ( this . document ) ) ;
49
+ }
50
+ }
51
+
52
+ class PublishedState implements State {
53
+ constructor ( private document : Document ) { }
54
+
55
+ render ( ) {
56
+ console . log ( "Rendering the document in Published state" ) ;
57
+ }
58
+
59
+ publish ( ) {
60
+ console . log ( "The document is already in Published state. Nothing to do." ) ;
61
+ }
62
+ }
63
+
64
+ const document = new Document ( ) ;
65
+
66
+ document . render ( ) ;
67
+ document . publish ( ) ;
68
+ document . publish ( ) ;
69
+ document . render ( ) ;
70
+ document . publish ( ) ;
You can’t perform that action at this time.
0 commit comments