设计模式-备忘录模式
不破坏封装的捕获并保存对象的内部状态,并可以在之后恢复保存的状态
我们拿现在汽车上常见的座椅记忆来举例
先定义座椅类,它有位置、高度和角度三个属性
@Data
@AllArgsConstructor
public class Seat {
private int position;
private int height;
private int angle;
public SeatMemento saveSeatMemento(){
return new SeatMemento(position, height, angle);
}
public void recoverySeat(SeatMemento memento){
this.position = memento.getPosition();
this.height = memento.getHeight();
this.angle = memento.getAngle();
}
}
座椅记忆会帮车主记住舒服的姿势,但是不需要车主知道具体的参数是什么
先定义一个备忘录类
@Data
@AllArgsConstructor
public class SeatMemento {
private int position;
private int height;
private int angle;
}
然后需要一个保管者
@Data
public class SeatCaretaker {
private SeatMemento memento;
}
座椅记忆的功能模拟如下
public class Demo {
public static void main(String[] args) {
Seat seat = new Seat(0, 0, 90);
System.out.println("最初的座椅状态:" + seat.toString());
seat.setPosition(10);
seat.setHeight(5);
seat.setAngle(110);
System.out.println("调到舒服的状态:" + seat.toString());
SeatCaretaker caretaker = new SeatCaretaker();
caretaker.setMemento(seat.saveSeatMemento());
seat.setPosition(20);
seat.setHeight(20);
seat.setAngle(160);
System.out.println("调到躺着的姿势睡了一觉:" + seat.toString());
seat.recoverySeat(caretaker.getMemento());
System.out.println("恢复到舒服的姿势:" + seat.toString());
}
}