Merge pull request #7423 from dupirefr/bael-3090

dupirefr/dupire.francois+pro@gmail.com [BAEL-3090] Memento Design Pattern
This commit is contained in:
Erik Pragt 2019-08-18 10:34:54 +10:00 committed by GitHub
commit 20f4c8dab5
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
5 changed files with 94 additions and 0 deletions

View File

@ -30,6 +30,12 @@
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>${commons-lang3.version}</version>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
<version>${assertj.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.inferred</groupId>
@ -49,6 +55,7 @@
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<intellij.annotations.version>16.0.2</intellij.annotations.version>
<assertj.version>3.12.2</assertj.version>
<freebuilder.version>2.4.1</freebuilder.version>
<javax.annotations.version>3.0.2</javax.annotations.version>
</properties>

View File

@ -0,0 +1,27 @@
package com.baeldung.memento;
public class TextEditor {
private TextWindow textWindow;
private TextWindowState savedTextWindow;
public TextEditor(TextWindow textWindow) {
this.textWindow = textWindow;
}
public void write(String text) {
textWindow.addText(text);
}
public String print() {
return textWindow.getCurrentText();
}
public void hitSave() {
savedTextWindow = textWindow.save();
}
public void hitUndo() {
textWindow.restore(savedTextWindow);
}
}

View File

@ -0,0 +1,26 @@
package com.baeldung.memento;
public class TextWindow {
private StringBuilder currentText;
public TextWindow() {
this.currentText = new StringBuilder();
}
public String getCurrentText() {
return currentText.toString();
}
public void addText(String text) {
currentText.append(text);
}
public TextWindowState save() {
return new TextWindowState(currentText.toString());
}
public void restore(TextWindowState save) {
currentText = new StringBuilder(save.getText());
}
}

View File

@ -0,0 +1,14 @@
package com.baeldung.memento;
public class TextWindowState {
private String text;
public TextWindowState(String text) {
this.text = text;
}
public String getText() {
return text;
}
}

View File

@ -0,0 +1,20 @@
package com.baeldung.memento;
import org.junit.jupiter.api.Test;
import static org.assertj.core.api.Assertions.assertThat;
class TextEditorUnitTest {
@Test
void givenTextEditor_whenAddTextSaveAddMoreAndUndo_thenSavecStateRestored() {
TextEditor textEditor = new TextEditor(new TextWindow());
textEditor.write("The Memento Design Pattern\n");
textEditor.write("How to implement it in Java?\n");
textEditor.hitSave();
textEditor.write("Buy milk and eggs before coming home\n");
textEditor.hitUndo();
assertThat(textEditor.print()).isEqualTo("The Memento Design Pattern\nHow to implement it in Java?\n");
}
}