Skip to content

Commit

Permalink
Add Memento pattern
Browse files Browse the repository at this point in the history
  • Loading branch information
peterm85 committed Nov 22, 2019
1 parent 50b8fa0 commit 393cb1b
Show file tree
Hide file tree
Showing 8 changed files with 145 additions and 1 deletion.
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,7 @@ Forma en que las clases u objetos interaccionan y distribuyen funcionalidades.
* [Observer](#observer) [**O**]
* [Strategy](#strategy) [**O**]
* [Chain of Responsability](#chain) [**O**]
* [Memento] [**O**]
* [Memento](#memento) [**O**]
* [Mediator] [**O**]
* [Templete method] [**C**]
* [Iterator] [**O**]
Expand Down Expand Up @@ -358,3 +358,18 @@ Cada elemento deberá tener referencia al siguiente.

**Ejemplos:**
* [Army](https://github.com/peterm85/design-patterns/tree/master/src/chain/examples/army)

## <a name="memento">Memento</a> [&#8593;](#lista-de-patrones)

**Propósito:** Almacenar el estado de un objeto (o del sistema completo) en un momento dado de manera que se pueda restaurar en ese punto de manera sencilla.

Se mantiene almacenado el estado del objeto para un instante de tiempo en una clase independiente de aquella a la que pertenece el objeto (pero sin romper la encapsulación), de forma que ese recuerdo permita que el objeto sea modificado y pueda volver a su estado anterior.

**Aplicación:** Usamos el patrón [Memento](https://github.com/peterm85/design-patterns/tree/master/src/memento/pattern) cuando...
* Se quiere poder restaurar el sistema desde estados pasado.
* Se desea facilitar el hacer y deshacer de determinadas operaciones, para lo que habrá que guardar los estados anteriores de los objetos sobre los que se opere (o bien recordar los cambios de forma incremental).

**Ejemplos:**
* [Time Machine](https://github.com/peterm85/design-patterns/tree/master/src/memento/examples/timemachine)

**Referencia:** [https://www.geeksforgeeks.org/memento-design-pattern/](https://www.geeksforgeeks.org/memento-design-pattern/)
20 changes: 20 additions & 0 deletions src/memento/examples/timemachine/Life.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
package memento.examples.timemachine;

public class Life {
private String time;

public void set(String time) {
System.out.println("Setting time to " + time);
this.time = time;
}

public Memento saveToMemento() {
System.out.println("Saving time to Memento");
return new Memento(time);
}

public void restoreFromMemento(Memento memento) {
time = memento.getSavedTime();
System.out.println("Time restored from Memento: " + time);
}
}
14 changes: 14 additions & 0 deletions src/memento/examples/timemachine/Memento.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package memento.examples.timemachine;

public class Memento {

private final String time;

public Memento(String timeToSave) {
time = timeToSave;
}

public String getSavedTime() {
return time;
}
}
25 changes: 25 additions & 0 deletions src/memento/examples/timemachine/TimeMachineClient.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
package memento.examples.timemachine;

import java.util.ArrayList;
import java.util.List;

public class TimeMachineClient {

public static void main(String[] args) {

List<Memento> savedTimes = new ArrayList<Memento>();

Life life = new Life();

//time travel and record the eras
life.set("1000 B.C.");
savedTimes.add(life.saveToMemento());
life.set("1000 A.D.");
savedTimes.add(life.saveToMemento());
life.set("2000 A.D.");
savedTimes.add(life.saveToMemento());
life.set("4000 A.D.");

life.restoreFromMemento(savedTimes.get(0));
}
}
17 changes: 17 additions & 0 deletions src/memento/pattern/Caretaker.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package memento.pattern;

import java.util.ArrayList;
import java.util.List;

public class Caretaker {

private List<Memento> savedStates = new ArrayList<Memento>();

public void addMemento(Memento m) {
savedStates.add(m);
}

public Memento getMemento(int index) {
return savedStates.get(index);
}
}
14 changes: 14 additions & 0 deletions src/memento/pattern/Memento.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package memento.pattern;

public class Memento {

private String state;

public Memento(String stateToSave){
state = stateToSave;
}

public String getSavedState(){
return state;
}
}
18 changes: 18 additions & 0 deletions src/memento/pattern/MementoTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package memento.pattern;

public class MementoTest {

public static void main(String[] args) {
Caretaker caretaker = new Caretaker();

Originator originator = new Originator();
originator.set("State1");
originator.set("State2");
caretaker.addMemento( originator.saveToMemento() );
originator.set("State3");
caretaker.addMemento( originator.saveToMemento() );
originator.set("State4");

originator.restoreFromMemento( caretaker.getMemento(1) );
}
}
21 changes: 21 additions & 0 deletions src/memento/pattern/Originator.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package memento.pattern;

public class Originator {

private String state;

public void set(String state) {
System.out.println("Originator: Setting state to "+state);
this.state = state;
}

public Memento saveToMemento(){
System.out.println("Originator: Saving to Memento.");
return new Memento(state);
}

public void restoreFromMemento(Memento m) {
state = m.getSavedState();
System.out.println("Originator: State after restoring from Memento: "+state);
}
}

0 comments on commit 393cb1b

Please sign in to comment.