Skip to content

Commit faba2e2

Browse files
authored
备忘录模式
备忘录模式
1 parent 7ad5e8f commit faba2e2

File tree

4 files changed

+99
-0
lines changed

4 files changed

+99
-0
lines changed
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
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+
}
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
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+
}

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy