Skip to content

Commit 434c1ae

Browse files
committed
完成 备忘录模式 Sample
1 parent dbcbc12 commit 434c1ae

File tree

3 files changed

+36
-0
lines changed

3 files changed

+36
-0
lines changed

memento/src/main/java/me/zbl/memento/Application.java

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,8 @@
2626
import org.slf4j.Logger;
2727
import org.slf4j.LoggerFactory;
2828

29+
import java.util.Stack;
30+
2931
/**
3032
* Memento
3133
*/
@@ -34,6 +36,30 @@ public class Application {
3436
private static final Logger LOGGER = LoggerFactory.getLogger(Application.class);
3537

3638
public static void main(String[] args) {
39+
Stack<Plant> stack = new Stack<>();
40+
41+
Flower flower = new Flower(FlowerType.SEED, "水仙花", 1, 2);
42+
stack.add(flower.getMemento());
43+
LOGGER.info(flower.toString());
44+
flower.growing();
45+
stack.add(flower.getMemento());
46+
LOGGER.info(flower.toString());
47+
flower.growing();
48+
stack.add(flower.getMemento());
49+
LOGGER.info(flower.toString());
50+
flower.growing();
51+
stack.add(flower.getMemento());
52+
LOGGER.info(flower.toString());
53+
flower.growing();
54+
stack.add(flower.getMemento());
55+
LOGGER.info(flower.toString());
56+
flower.growing();
57+
stack.add(flower.getMemento());
58+
LOGGER.info(flower.toString());
3759

60+
while (stack.size() > 0) {
61+
flower.setMemento(stack.pop());
62+
LOGGER.info(flower.toString());
63+
}
3864
}
3965
}

memento/src/main/java/me/zbl/memento/Flower.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,11 @@ void setMemento(Plant plant) {
7171
setWeight(flowerMemento.getWeight());
7272
}
7373

74+
@Override
75+
public String toString() {
76+
return String.format("名称:%s\t状态:%s\t质量:%d克\t高度:%d厘米", getName(), getType(), getWeight(), getHeight());
77+
}
78+
7479
public Flower(FlowerType type, String name, int height, int weight) {
7580
this.type = type;
7681
this.name = name;

memento/src/main/java/me/zbl/memento/FlowerType.java

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,4 +35,9 @@ public enum FlowerType {
3535
FlowerType(String name) {
3636
this.name = name;
3737
}
38+
39+
@Override
40+
public String toString() {
41+
return name;
42+
}
3843
}

0 commit comments

Comments
 (0)