定義:保存一個(gè)對(duì)象的某個(gè)狀態(tài),以便在適當(dāng)?shù)臅r(shí)候恢復(fù)對(duì)象
特點(diǎn):
1、給用戶提供了一種可以恢復(fù)狀態(tài)的機(jī)制,可以使用戶能夠比較方便地回到某個(gè)歷史的狀態(tài)。
2、實(shí)現(xiàn)了信息的封裝,使得用戶不需要關(guān)心狀態(tài)的保存細(xì)節(jié)。
企業(yè)級(jí)應(yīng)用和常用框架中的應(yīng)用:常見(jiàn)文本編輯器使用了該模式
實(shí)例:
注意:該實(shí)例中只有撤銷操作,沒(méi)有向前還原操作
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
|
/** * 目標(biāo)對(duì)象:將要被備忘的對(duì)象 */ class Word { private String content; private String image; private String table; public Word(String content, String image, String table) { super(); this.content = content; this.image = image; this.table = table; } public WordMemento memento(){ return new WordMemento(this); } public void recovery(WordMemento memento){ this.content = memento.getContent(); this.image = memento.getImage(); this.table = memento.getTable(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } } /** * 備忘錄對(duì)象 */ class WordMemento{ private String content; private String image; private String table; public WordMemento(Word word) { this.content = word.getContent(); this.image = word.getImage(); this.table = word.getTable(); } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public String getImage() { return image; } public void setImage(String image) { this.image = image; } public String getTable() { return table; } public void setTable(String table) { this.table = table; } } /** * 負(fù)責(zé)人對(duì)象:負(fù)責(zé)記錄備忘錄對(duì)象 */ class CareTaker{ private List<WordMemento> list = new ArrayList<>(); private int index = 0; public void setMemento(WordMemento memento){ list.add(memento); this.index = list.size(); } public WordMemento getWordMemento(){ if (index == 0){ System.out.println( "沒(méi)有可還原的內(nèi)容" ); return null; } WordMemento memento = list.get(index-1); list.remove(index-1); index--; return memento; } } |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。