Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions DesignPatterns/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ with practical examples and best practices for using design patterns to create r
- [Chain of Responsibility](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/chain/of/responsibility) 🔗
- [Command](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/command) 📝
- [Execute Around Method (EAM)](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/eam) ⭕
- [Memento](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/memento) 💾
- [Observer](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/observer) 👀
- [State](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/state) 📜
- [Strategy](src/main/java/pl/mperor/lab/java/design/pattern/behavioral/strategy) 🎯
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
package pl.mperor.lab.java.design.pattern.behavioral.memento;

import java.util.ArrayDeque;
import java.util.Deque;

class History {

private final Deque<TextMemento> history = new ArrayDeque<>();

void save(TextEditor editor) {
history.push(editor.save());
}

void undo(TextEditor editor) {
if (!history.isEmpty()) {
editor.restore(history.pop());
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package pl.mperor.lab.java.design.pattern.behavioral.memento;

class TextEditor {

private StringBuilder content = new StringBuilder();

TextEditor write(String text) {
content.append(text);
return this;
}

TextMemento save() {
return new TextMemento(content.toString());
}

void restore(TextMemento memento) {
content = new StringBuilder(memento.content());
}

String getContent() {
return content.toString();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
package pl.mperor.lab.java.design.pattern.behavioral.memento;

record TextMemento(String content) {
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package pl.mperor.lab.java.design.pattern.behavioral.memento;

import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;

public class TextEditorMementoTest {

@Test
public void testSavingAndRestoringWithTextMemento() {
var editor = new TextEditor();
var history = new History();

editor.write("⭐");
Assertions.assertEquals("⭐", editor.getContent());
history.save(editor);

editor.write("1️⃣").write("2️⃣").write("3️⃣");
Assertions.assertEquals("⭐1️⃣2️⃣3️⃣", editor.getContent());

history.undo(editor);
Assertions.assertEquals("⭐", editor.getContent());
}
}