Prepare a class that duplicates the state of a specific class and call it Memento. When user creates a duplicate, it instantiates Memento and records it in a collection, and retrieves the instance as needed.
Check with the following class structure
class | Explanation |
---|---|
Origin.class | Class to be replicated |
Memento.class | When duplicating Origin, duplicate Origin data in Memento and save Memento |
MementoList.class | Holds a collection (List, Map, etc.) and stores a Memento instance |
user(Main.class) | Check the operation |
Origin.class
class Origin{
int No;
void setNo(int No){
this.No=No;
}
Memento createMemento(){
return new Memento(No);
}
}
Memento.class
class Memento{
int No; //Have the same field as Origin
Memento(int No){
this.No=No;
}
int getNo(){
return No;
}
}
MementoList.class
class MementoList{
Map map = new HashMap();
void put(int key,Memento mmt){
map.put(key,mmt);
}
Memento getMemento(int key){
return (Memento) map.get(key);
}
}
user(Main.class)
public static void main(String[] args){
Origin or = new Origin();
MementoList list = new MementoList();
or.setNo(1);
list.put(1,or.createMemento());
or.setNo(2);
list.put(2,or.createMemento());
Memento m1 = list.getMemento(1);
System.out.println(m1.getNo());
}
Recommended Posts