-
Notifications
You must be signed in to change notification settings - Fork 2
/
State.ts
76 lines (62 loc) · 1.69 KB
/
State.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
class DocumentItem {
public text: string;
private state: DocumentItemState
getState() {
return this.state
}
setState(state: DocumentItemState) {
this.state = state;
this.state.setContext(this)
}
constructor() {
this.setState(new DraftDocumentItemState())
}
publishDoc() {
this.state.publish()
}
deleteDoc() {
this.state.delete()
}
}
abstract class DocumentItemState {
public name: string;
public item: DocumentItem;
public setContext(item: DocumentItem) {
this.item = item;
}
public abstract publish(): void;
public abstract delete(): void;
}
class DraftDocumentItemState extends DocumentItemState {
constructor() {
super();
this.name = 'DraftDocumentItemState'
}
public publish(): void {
console.log(`На сайт отправлен текст ${this.item.text}`)
this.item.setState(new PublishDocumentItemState())
}
public delete(): void {
console.log(`Документ удалён`)
}
}
class PublishDocumentItemState extends DocumentItemState {
constructor() {
super();
this.name = 'PublishDocumentItemState'
}
public publish(): void {
console.log(`Нельзя опубликовать опубликованый документ`)
}
public delete(): void {
console.log(`Снято с публикации`)
this.item.setState(new DraftDocumentItemState())
}
}
const item = new DocumentItem();
item.text = 'Первый пост'
console.log(item.getState())
item.publishDoc()
console.log(item.getState())
item.deleteDoc()
console.log(item.getState())