File tree Expand file tree Collapse file tree 4 files changed +99
-0
lines changed
java-des/src/com/java/design/memento Expand file tree Collapse file tree 4 files changed +99
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .java .design .memento ;
2+
3+ /**
4+ * 用于保存
5+ *
6+ * @author Administrator
7+ *
8+ */
9+ public class Caretaker {
10+
11+ private Memento memento ;
12+
13+ public Memento getMemento () {
14+ return memento ;
15+ }
16+
17+ public void setMemento (Memento memento ) {
18+ this .memento = memento ;
19+ }
20+
21+ }
Original file line number Diff line number Diff line change 1+ package com .java .design .memento ;
2+
3+ public class Memento {
4+
5+ private String state ;
6+
7+ public Memento (String state ) {
8+
9+ this .state = state ;
10+ }
11+
12+ public String getState () {
13+ return state ;
14+ }
15+
16+ public void setState (String state ) {
17+ this .state = state ;
18+ }
19+
20+ }
Original file line number Diff line number Diff line change 1+ package com .java .design .memento ;
2+
3+ /**
4+ * 备忘录模式 -----> 在不破坏封闭的前提下,捕获一个对象的内部状态,并在该对象之外保存这个状态。这样以后就可将该对象恢复到原先保存的状态
5+ *
6+ * @author Administrator
7+ *
8+ */
9+ public class MementoPattern {
10+
11+ public static void main (String [] args ) {
12+
13+ Originator originator = new Originator ();
14+ originator .setState ("在洗澡 ..." );
15+ originator .showState ();
16+
17+ // 状态进行保存
18+ Caretaker caretaker = new Caretaker ();
19+ caretaker .setMemento (originator .createMemento ());
20+
21+ originator .setState ("在吃饭 ..." );
22+ originator .showState ();
23+
24+ // 重新将状态拿出来
25+ originator .setMemento (caretaker .getMemento ());
26+ originator .showState ();
27+ }
28+
29+ }
Original file line number Diff line number Diff line change 1+ package com .java .design .memento ;
2+
3+ public class Originator {
4+
5+ private String state ;
6+
7+ public String getState () {
8+ return state ;
9+ }
10+
11+ public void setState (String state ) {
12+ this .state = state ;
13+ }
14+
15+ public Memento createMemento () {
16+ return new Memento (state );
17+ }
18+
19+ public void setMemento (Memento memento ) {
20+
21+ state = memento .getState ();
22+ }
23+
24+ public void showState () {
25+
26+ System .out .println (state );
27+ }
28+
29+ }
You can’t perform that action at this time.
0 commit comments